我编写此代码是为了遍历目录并查找大于 300MB 的文件。
但是,我得到了很多重复值,并且文件之间的重复值数量各不相同。谁能解释一下或者为我改进代码?
import os
path = 'C:\\Users\\brentond\\Desktop\\Lower Thames Crossing'
for foldername, subfolders, filenames in os.walk(path):
for subfolder in subfolders:
for filename in filenames:
if os.path.getsize(os.path.join(foldername, filename))>300000000:
print(foldername + '\\' + filename)
最佳答案
您不必自己探索子文件夹,walk为你做。
来自文档:
os.walk(top, topdown=True, onerror=None, followlinks=False)
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
(强调我的)
所以,只需这样做:
import os
path = 'C:\\Users\\brentond\\Desktop\\Lower Thames Crossing'
for foldername, subfolders, filenames in os.walk(path):
for filename in filenames:
if os.path.getsize(os.path.join(foldername, filename))>300000000:
print(foldername + '\\' + filename)
关于python - 在 Python 中使用 os.walk 查找大于 300MB 的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59154844/