我正在尝试打印预定义路径中的文件名,这些路径存储在path.txt中。但是,当我执行以下代码时,没有任何错误,也没有打印文件名。
import os
with open('D:\paths.txt', 'r') as file:
data = file.read()
path = data.split(";")
print(path)
for line in path:
for root, dirs, files in os.walk(line):
for name in files:
print(name)
使用path = data.split(";")
,path
已经是路径列表(尽管带引号)。进行for line in path:
会不必要地遍历路径的每个字符。
您可以通过删除for line in path:
并去除双引号来解决此问题:
import os
with open('D:\paths.txt', 'r') as file:
for path in data.split(';'):
for root, _, files in os.walk(path.strip('"')):
for name in files:
print(name)