[英]Python open() gives "FileNotFoundError: [Errno 2] No such file or directory:", but the file exists
I'm trying to read all the files in a directory and append the text in them into a list but I get the error in the header.我正在尝试将目录中的所有文件和 append 中的文本读取到列表中,但我在 header 中收到错误。 However, the file actually exists.
但是,该文件确实存在。 My code is:
我的代码是:
pos_lines = []
train_pos_path = r'C:\Users\Halid\Desktop\nlp_p5\nlp_dir2\TRAIN\posTr'
# print(os.listdir(train_pos_path))
for filename in os.listdir(train_pos_path):
with open(filename, "r",encoding="utf-8", errors='ignore') as f:
for line in f.readlines():
pos_lines.append(line)
The path is the absolute path of the directory and print(os.listdir(train_pos_path))
gives the list of the files under that directory.路径是目录的绝对路径,
print(os.listdir(train_pos_path))
给出了该目录下的文件列表。 However, I can't open the files in it and it gives me the error I mentioned.但是,我无法打开其中的文件,它给了我我提到的错误。 My code I'm trying to run is in "C:\Users\Halid\Desktop\nlp_p5" .
我尝试运行的代码位于"C:\Users\Halid\Desktop\nlp_p5"中。 Does anybody know why I'm getting this error and how can I solve this?
有谁知道我为什么会收到这个错误,我该如何解决这个问题?
You've specified an absolute path to the directory, r'C:\Users\Halid\Desktop\nlp_p5\nlp_dir2\TRAIN\posTr'
.您已指定目录的绝对路径
r'C:\Users\Halid\Desktop\nlp_p5\nlp_dir2\TRAIN\posTr'
。 You then proceeded to list all files with their filenames, receiving A
, B
, C
, ...然后,您继续列出所有文件及其文件名,接收
A
, B
, C
,...
However, A
, B
, C
, ... are not located in the directory you're running your python script.但是,
A
, B
, C
, ... 不在您运行 python 脚本的目录中。 Try calling试着打电话
os.chdir(train_pos_path)
before calling the for loop
.在调用
for loop
之前。
Another solution would be to prepend each path with train_pos_path
:另一种解决方案是在每条路径前面加上
train_pos_path
:
train_pos_path = r'C:\Users\Halid\Desktop\nlp_p5\nlp_dir2\TRAIN\posTr'
for filename in os.listdir(train_pos_path):
with open(os.path.join(train_pos_path, filename), "r",encoding="utf-8", errors='ignore') as f:
for line in f.readlines():
pos_lines.append(line)
The key takeaway from this is the fact that os.listdir(directory)
returns just the names as seen from the directory
, not their absolute paths.关键在于
os.listdir(directory)
只返回从directory
中看到的名称,而不是它们的绝对路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.