错误:Errno 2 没有这样的文件或目录:Python 无法找到已经存在的文件

这是我写的读取目录中文件的代码

该代码第一次运行良好,但此后出现错误:[Errno 2] 没有这样的文件或目录:'ISS_Ackermann.data.amd'

代码:

path = r'C:\Users\Tarun\Desktop\ISS_Ackermann\Platformlibrary\Package\VehicleDynamicsController\ISS\Feedforward'

# Read every file in directory
for filename in os.listdir(path):
    with open(filename,"r") as f:
        # Read each line of the file
        for line in f.readlines():
            bs_data = bs_data + line

with io.open("shouldget.xml","w",encoding='utf-8') as output: 
    output.write(str(bs_data)) 
       
print(bs_data) 

我已经尝试过针对类似问题给出的方法,但没有任何效果

附加信息: IDE:Jupyter

错误:Errno 2 没有这样的文件或目录:Python 无法找到已经存在的文件

q4623051 回答:错误:Errno 2 没有这样的文件或目录:Python 无法找到已经存在的文件

调用 open 时需要有完整路径

with open(filename,"r") as f:

应该

with open(os.path.join(path,filename),"r") as f:
,

对您的代码进行小幅修改应该会有所帮助。这给出了当您尝试打开文件时文件所在位置的绝对路径。

for filename in os.listdir(path):
    with open(os.path.join(path,"r") as f:
        # Read each line of the file
        for line in f.readlines():
,

您的笔记本不在您要查找文件的目录中。 Python 在该目录中搜索,最终引发错误。

所以,使用文件的绝对路径

for filename in os.listdir(path):
    with open(os.path.join(path,"r"
,

调试这种情况的一个好方法是将目录更改为变量 path 并检查 python 看到的内容。

os.chdir(path)
os.listdir(path)

您可能不在您认为的目录中,这会对您有所帮助。

使用 os.listdir() 后,您可以了解“您所在的位置”,并根据文件所在的位置相应地更改路径。

本文链接:https://www.f2er.com/2557.html

大家都在问