python实现文件夹遍历
2023-09-27 14:27:48 时间
python 3
import os
def main():
parent_path = "K:\develop\project\php\demo\youmeng";
# 批量添加namespace|
# 列出windows目录下的所有文件和文件名
for (root, dirs, files) in os.walk(parent_path):
for filename in files:
filename_full_path = os.path.join(root, filename)
print(filename_full_path)
for dirc in dirs:
dir_full_name= os.path.join(root, dirc);
print(dir_full_name)
pass
if __name__ == '__main__':
main()
python 中os.path模块用于操作文件或文件夹
os.path.exists(path) 判断文件路径是否存在
dir = "c:\windows"
if os.path.exists(dir) :
print "dir exists"
else :
print "no exists"
os.path.isfile(path) 判断path是否是文件
dir = "c:\windows\system32\cmd.exe"
if os.path.isfile(dir) :
print "file exists"
else :
print "no exists"
os.path.getsize(path) 获取path文件的大小
size = os.path.getsize(dir)
print size/1024
os.path.walk(path) 遍历path,返回一个三元组(dirpath, dirnames, filenames). dirpath表示遍历到的路径, dirnames表示该路径下的子目录名,是一个列表, filesnames表示该路径下的文件名,也是一个列表. 例如: 当遍历到c:\windows时,dirpath="c:\windows", dirnames是这个路径下所有子目录名的列表,dirnames是这个路径下所有文件名的列表
for (root, dirs, files) in os.walk("C:\windows"): 列出windows目录下的所有文件和文件名
for filename in files:
print os.path.join(root,filename)
for dirc in dirs:
print os.path.join(root,dirc)
问题 1 获取给定文件夹的大小?
要遍历文件的大小,只需要遍历文件内的所有文件,然后将所有文件夹的大小加起来
def getDirSzie(dir) :
for (root,dirs,files) in os.walk(dir,False) :
Size = 0
for filename in files :
Size += os.path.getsize(os.path.join(root,filename))
print root,Size/1024
问题 2 遍历一个文件夹的子目录,不遍历子目录的字目录?
os.listdir(path) 函数列出指定目录下的文件和文件夹
dir = 'c:/windows'
if os.path.exists(dir):
dirs = os.listdir(dir)
for dirc in dirs:
print dirc
else :
print "dir not exists"
问题3 删除指定目录下空的目录
for (root, dirs, files) in os.walk(path) :
for item in dirs :
dir = os.path.join(root, item)
try :
print dir
os.rmdir(dir)
except :
pass
问题4 修改指定目录下所有文件的文件后缀
for (root,dirs,files) in os.walk(path) :
for item in files :
d = os.path.join(root, item)
name = d + ".eml"
os.rename(d, name)
相关文章
- Python遍历文件夹
- 时间序列预测|基于多元线性回归算法负荷预测(Python代码实现)
- Python中异常重试解决方案
- python-day7 for语句循环遍历各种数据类型的场景
- 【Python】字典元素的 遍历
- IndexError: invalid index of a 0-dim tensor. Use `tensor.item()` in Python
- Python 列表(List) 的三种遍历(序号和值)方法
- (九)Python中的collections模块
- PyQt(Python+Qt)学习随笔:Qt Designer中主窗口对象unifiedTitleAndToolBarOnMac属性
- Python numpy.empty函数方法的使用
- python 处理中文Excel
- Python-循环遍历文件
- Python爬虫,真的可以快速入门吗?NO!
- python sqlite3
- Python 代理爬取网站数据
- python--AutoPy库
- 四十五、python学习之Djnago(DRF框架一):介绍、序列化/反序列化及环境搭建