Python 错误:文件不存在';不存在并且没有这样的文件或目录
我有要迭代的文件(data1.txt、data2.txt等),所以 我做到了:Python 错误:文件不存在';不存在并且没有这样的文件或目录,python,python-3.x,os.walk,Python,Python 3.x,Os.walk,我有要迭代的文件(data1.txt、data2.txt等),所以 我做到了: path='mypath' # not the same python project directory for root, dirs, files in os.walk(path): for file in files: print(file) f = open(file) 尽管存在这些文件,但这表明: data1.txt FileNotFoundError: [Errno
path='mypath' # not the same python project directory
for root, dirs, files in os.walk(path):
for file in files:
print(file)
f = open(file)
尽管存在这些文件,但这表明:
data1.txt
FileNotFoundError: [Errno 2] No such file or directory: 'data1.txt'
我还有一个函数,我想在其中使用这些文件,当我使用位于同一python项目目录中的单个文件时,这个函数可以很好地工作
process_r=pro_r("data1.txt")
但是,当我在上面的for循环中使用它时,process\r=pro\r(file),它显示了这个错误:file不存在问题是os.walk返回给定路径的相对路径。因此,您需要使用以下路径:
path='mypath' # not the same python project directory
for root, dirs, files in os.walk(path):
for file in files:
print(file)
f = open(path + "/" + file) # / or \\ depends on your OS
您需要加入root和file以获得文件的正确路径:
path='mypath' # not the same python project directory
for root, dirs, files in os.walk(path):
for file in files:
print(root, file)
f = open(os.path.join(root, file))
避免手动加入路径。查看我的答案以获得更好的解决方案