如何使用 python 遍历路径并查找文件和目录?
how to traverse path and find files and directories using python?
我有一个 python 代码遍历给定路径并列出所有文件和目录,但问题是当文件存在于子目录中时系统崩溃并显示 FileNotFoundError 该文件不存在于给定路径及其权利中,因为它显示 path/file 而不是 路径 /folder/file
我该如何解决这个错误?
代码:
for dirpath, dirnames, files in os.walk(src):
print(f'Found directory: {dirpath}')
# for file_name in files:
if len(dirnames)==0 and len(files)==0:
print("this directory is empty")
else:
print(files)
for name in files:
full_file_name = os.path.join(src, name)
print("files: ",full_file_name)
full_file_name = os.path.join(src, name)
应该是 full_file_name = os.path.join(dirpath, name)
我有一个 python 代码遍历给定路径并列出所有文件和目录,但问题是当文件存在于子目录中时系统崩溃并显示 FileNotFoundError 该文件不存在于给定路径及其权利中,因为它显示 path/file 而不是 路径 /folder/file
我该如何解决这个错误?
代码:
for dirpath, dirnames, files in os.walk(src):
print(f'Found directory: {dirpath}')
# for file_name in files:
if len(dirnames)==0 and len(files)==0:
print("this directory is empty")
else:
print(files)
for name in files:
full_file_name = os.path.join(src, name)
print("files: ",full_file_name)
full_file_name = os.path.join(src, name)
应该是 full_file_name = os.path.join(dirpath, name)