递归遍历目录和文件

import os

path = r'F:\PycharmProjects\basic gram\作业和习题\test'

def getAllFileAndDir(path):
# 获取当前目录下所有文件及文件目录
fileList = os.listdir(path)
# print(fileList) # 遍历fileList列表
for fileName in fileList:
# isdir isfile
# print(fileName)
# 拼接绝对路径
absFile = os.path.join(path,fileName)
if os.path.isdir(absFile):
print(absFile+'---目录')
getAllFileAndDir(absFile)
else:
print(absFile+'---文件')
getAllFileAndDir(path)

栈 深度遍历

import collections

def getAllFileAndDir(sourcePath):

    stack = collections.deque()
stack.append(sourcePath)
while len(stack) != 0:
path = stack.pop()
fileList = os.listdir(path)
for fileName in fileList:
absFile = os.path.join(path, fileName)
if os.path.isdir(absFile):
print(absFile+'---目录')
stack.append(absFile)
else:
print(absFile+'---文件') getAllFileAndDir(path)

队列 广度遍历

def getAllFileAndDir(sourcePath):

    queue = collections.deque()
queue.append(sourcePath) while len(queue) !=0:
path = queue.popleft()
fileList = os.listdir(path)
for fileName in fileList:
absFile = os.path.join(path, fileName)
if os.path.isdir(absFile):
print(absFile+'---目录')
queue.append(absFile)
else:
print(absFile+'---文件') getAllFileAndDir(path)

复制目录和文件

import os
# 复制目录
def copyDir(sourDir,targetDir):
if not os.path.exists(sourDir):
print("如果源目录不存在,直接停止")
return if not os.path.exists(targetDir):
os.makedirs(targetDir) listName = os.listdir(sourDir)
for dirNameAndFileName in listName:
sourAbsPath = os.path.join(sourDir,dirNameAndFileName)
targetAbsPath = os.path.join(targetDir,dirNameAndFileName)
if os.path.isdir(sourAbsPath):
copyDir(sourAbsPath,targetAbsPath)
if os.path.isfile(sourAbsPath):
# 如果目标文件不存在, 或者 如果该文件已经存在但是文件大小不一样
if (not os.path.exists(targetAbsPath)) or (os.path.exists(targetAbsPath) and (os.path.getsize(sourAbsPath) != os.path.getsize(targetAbsPath))):
rf = open(sourAbsPath,"rb")
wf = open(targetAbsPath,"wb")
while True:
content = rf.read(1024*1024)
if len(content) == 0:
break
wf.write(content)
wf.flush()
wf.close()
rf.close() sPath = r'F:\PycharmProjects\basic gram\作业和习题\test'
tPath = r'F:\PycharmProjects\basic gram\作业和习题\testNew'
copyDir(sPath, tPath)

文件复制实例

1.一个函数接受文件夹的名称作为输入参数,请将该文件夹中的所有文件复制到 文件夹名-副本 中去,请补充缺失的代码. (20分)
def copyFile(sPath)
2.题1复制过程中,每隔一秒打印一次复制进度(即当前已复制个数/总文件个数)(15分)

 
import os
import collections
import time
import sys
def getFileNum(sPath):
num = 0
stack = collections.deque()
stack.append(sPath)
while len(stack) != 0:
path = stack.pop()
fileList = os.listdir(path)
for fileName in fileList:
absFile = os.path.join(path, fileName)
if os.path.isdir(absFile):
stack.append(absFile)
else:
num += 1
return num def copyFile(sPath):
tPath = r'F:\PycharmProjects\basic gram\作业和习题\Anaconda3-副本'
stack1 = collections.deque()
stack1.append(sPath)
stack2 = collections.deque()
stack2.append(tPath)
timepoint = 1
filenum = 0
while len(stack1) != 0:
sPath = stack1.pop()
tPath = stack2.pop()
if not os.path.exists(tPath):
os.makedirs(tPath)
listName = os.listdir(sPath)
for filename in listName:
absfile = os.path.join(sPath, filename)
tabsfile = os.path.join(tPath, filename)
if os.path.isdir(absfile):
stack1.append(absfile)
stack2.append(tabsfile)
else:
rf = open(absfile, 'rb')
wf = open(tabsfile, 'wb')
while True:
content = rf.read(1024*1024)
if len(content) == 0:
break
wf.write(content)
# 刷新缓冲区
wf.flush()
if time.clock()//1 == timepoint:
sys.stdout.write('\r进度:%d/%d'%(filenum,num))
timepoint += 1
wf.close()
rf.close()
filenum += 1
sys.stdout.write('\r进度:%d/%d' % (num, num)) sPath = r'F:\PycharmProjects\basic gram\作业和习题\Anaconda3' num = getFileNum(sPath)
# print(num)
start_time = time.clock()
copyFile(sPath)

阅读原文

python 文件目录遍历的更多相关文章

  1. python文件目录遍历保存成xml文件代码

    Linux服务器有CentOS.Fedora等,都预先安装了Python,版本从2.4到2.5不等,而Windows类型的服务器也多数安装了Python,因此只要在本机写好一个脚本,上传到对应机器,在 ...

  2. Android安全开发之ZIP文件目录遍历

    1.ZIP文件目录遍历简介 因为ZIP压缩包文件中允许存在“../”的字符串,攻击者可以利用多个“../”在解压时改变ZIP包中某个文件的存放位置,覆盖掉应用原有的文件.如果被覆盖掉的文件是动态链接s ...

  3. python 实时遍历日志文件

    首先尝试使用 python open 遍历一个大日志文件, 使用 readlines() 还是 readline() ? 总体上 readlines() 不慢于python 一次次调用 readlin ...

  4. Android 安全开发之 ZIP 文件目录遍历

    1.ZIP文件目录遍历简介 因为ZIP压缩包文件中允许存在"../"的字符串,攻击者可以利用多个"../"在解压时改变ZIP包中某个文件的存放位置,覆盖掉应用原 ...

  5. Python文件遍历二种方法

    分享下有关Python文件遍历的两种方法,使用的OS模块的os.walk和os.listdir实现. 关于Python的文件遍历,大概有两种方法,一种是较为便利的os.walk(),还有一种是利用os ...

  6. Python简单遍历字典及删除元素的方法

    Python简单遍历字典及删除元素的方法 这篇文章主要介绍了Python简单遍历字典及删除元素的方法,结合实例形式分析了Python遍历字典删除元素的操作方法与相关注意事项,需要的朋友可以参考下 具体 ...

  7. python+selenium遍历某一个标签中的内容

    一.python+selenium遍历某一个标签中的内容 举个例子:我要获取列表标签<li></li>的内容 根据python+selenium定位到列表整体,使用for循环获 ...

  8. python栈、队列、文件目录遍历

    一. 栈与队列 关注公众号"轻松学编程"了解更多. 1. 栈 stack 特点:先进先出[可以抽象成竹筒中的豆子,先进去的后出来] 后来者居上 mystack = [] #压栈[向 ...

  9. python中遍历文件的3个方法

    转自: http://www.jb51.net/article/54640.htm 用python进行文件遍历有多种方法,这里列举并说明一下. os.path.walk() 这是一个传统的用法. wa ...

随机推荐

  1. 转 解决configure: error: Please reinstall the libcurl distribution

    今天配置一台server的php支持curl的时候, 出现如下报错 checking for cURL in default path... not foundconfigure: error: Pl ...

  2. Appium原理及版本变化细节

    Appium原理小结 Api接口调用selenium的接口,Android底层用android的instrumentation(API2.3+ 通过绑定另外一个独立的selendroid项目来实现的) ...

  3. LR接口性能测试提示Code - 60990 Error: Two Way Communication Error: Function two_way_comm_post_message / two_ (转载)

    一.在做JAVA接口性能测试时,场景在运行中出现:Code - 60990 Error: Two Way Communication Error: Function two_way_comm_post ...

  4. Git 经常使用命令合集

    ====== Git 经常使用命令合集 ====== === 1.Git 文档 ===     Git 中文文档观看地址:http://git.oschina.net/progit/      === ...

  5. ACM退役前2个月总结

    这个时候是该好好地反省一下自己了!曾经的时候为了队伍能打出很多其它的题,我硬是看了ACM的非常多模块!也会了非常多的模板!可是如今我痛苦地发现比赛还是我一人单挑的局面!如今我也遇见了一个瓶颈了,那就是 ...

  6. How to Land your Dream Job

           今天在code school上面看到一个外国人写的文章,写的很棒,瞧一下外国人的思维和我们有什么不同?分享给所有的朋友       You know how some things ar ...

  7. CTF SQL注入知识点

    理解常用的登录判断 select * from user where username='admin' and password='123' 数据库元信息 infomation_schema 懂PHP ...

  8. 工欲善其事,必先利其器 软件工具开发关键词 protractor自动化测试工具 RegexBuddy正则 CodeSmith,LightSwitch:代码生成 CheatEngine:玩游戏修改内存值必备神器 ApkIDE:Android反编译工具 Reflector:反编译dll动态链接库

    工欲善其事,必先利其器 本文版权归翟士丹(Stan Zhai)和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利. 原文地址:http ...

  9. (转)失败和拒绝,也是一种肯定 找工作时,我四处碰壁这一段经历对自己职业生涯的帮助最大。为什么? "因为这些挫折让我的脸皮变厚了 如果你不是每天被人拒绝,那就说明你的人生目标不够远大 所谓成功,就是不停地经历失败,并且始终保持热情

    (转)失败和拒绝,也是一种肯定 昨天,先是看到一个老外,说了一句很震撼的话. "你个人的项目,应该有四分之一会失败,否则就说明你的冒险精神不够." (Expect and hope ...

  10. vim自动缩进设置

    需要软件 vim 下载地址 http://www.vim.org   code_complete.vim 插件 http://www.vim.org/scripts/script.php?script ...