def traverse_dir(path: str, allfile: list):
filelist = os.listdir(path)
for filename in filelist:
filepath = os.path.join(path, filename)
if os.path.isdir(filepath):
traverse_dir(filepath, allfile)
else:
allfile.append(filepath)
print("ok")
return allfile
if __name__ == '__main__':
filelists = []
print(traverse_dir(r'H:\2021-0003\恢复提取的数据\图片文件(PNG)、电子文档(DOC、DOCX、WPS)、电子表格(XLS、XLSX、ET)\2021-0003-JC01\Partition1', filelists))我有一个问题,当我使用Python os.listdir与目录路径,我得到一个错误,文件找不到,我的文件名包括“。
错误:
FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'H:\\2021-0003\\恢复提取的数据\\图片文件(PNG)、电子文档(DOC、DOCX、WPS)、电子表格(XLS、XLSX、ET)\\2021-0003-JC01\\Partition1\\Root\\Documents and Settings\\Administrator\\AppData\\Local\\Kingsoft\\WPS Cloud Files\\userdata\\qing\\filecache\\.343623948\\cachedata\\0D853AE97AA040BAA4381F40FD50701A_temp'但我打开文件,它就存在了。
发布于 2021-01-15 18:55:38
为了解决您的问题,您可以使用以下代码(在Python 3.7上测试):
import os
from pathlib import Path
def traverse_dir(basep: str, allfile: list):
# iterate over each item in the current path
for entry in os.scandir(basep):
# if the current item is accessible in your OS (and current item is not hidden, proceed)
# comment out the and part if you want hidden files to be included
if os.access(entry, os.R_OK) and not entry.name.startswith('.'):
# if current item is a directory, perform depth first walk
if entry.is_dir():
#print(entry.path)
traverse_dir(entry.path, allfile)
# else, add name of item to our list of files
else:
allfile.append(entry.name)
return allfile
def main():
basepath = Path(r'H:\2021-0003\恢复提取的数据\图片文件(PNG)、电子文档(DOC、DOCX、WPS)、电子表格(XLS、XLSX、ET)\2021-0003-JC01\Partition1')
filelist = []
print(traverse_dir(basepath, filelist))
if __name__ == '__main__':
main()请验证这是否适用于您。
Caution:递归需要很长时间!
https://stackoverflow.com/questions/65732041
复制相似问题