文件存在于目录中,但正在获取 "No such file or directory: 'I_90-0-109_(90).txt'"

file exist in the directory, but getting "No such file or directory: 'I_90-0-109_(90).txt'"

我是 Python 的初学者。我正在尝试 运行 以下代码来替换 .txt 注释文件中的一些标签。

import os

for txt_in in os.listdir(r"/home/masoud/masoud/Dataset/PID-CORRECTED/uncorrected-YOLO_darknet"):#https://www.newbedev.com/python/howto/how-to-iterate-over-files-in-a-given-directory/ 
    with open(txt_in) as infile:# In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.
        for line in infile:
            word=line.split(" ")[0]#spliting the string and returning an array and returing the first item of array
            if word=="6":
                word.replace('6', '5')#should i use if statement?
            elif word=="9":
                word.replace('9', '6')
            elif word=="10":
                word.replace('10', '7')
            elif word=="11":
                word.replace('11', '8')#how does it close one txt and open the next one?
                #If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.
            else:
                continue
            break

但我收到以下错误:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-7-10f3bd0ebffc> in <module>
      2 
      3 for txt_in in os.listdir("/home/masoud/masoud/Dataset/PID-CORRECTED/uncorrected-YOLO_darknet"):#https://www.newbedev.com/python/howto/how-to-iterate-over-files-in-a-given-directory/
----> 4     with open(txt_in) as infile:# In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.
      5         for line in infile:
      6             word=line.split(" ")[0]#spliting the string and returning an array and returing the first item of array

FileNotFoundError: [Errno 2] No such file or directory: 'I_90-0-109_(90).txt'

好像可以在地址目录下找到.txt文件,如果是为什么会说No such file or directory: 'I_90-0-109_(90).txt'? 请帮助。谢谢!

问题是os.listdir只列出文件名,不包括目录。所以你需要自己在前面加上目录名:

dirname = "/home/masoud/masoud/Dataset/PID-CORRECTED/uncorrected-YOLO_darknet"
for txt_in in os.listdir(dirname):
    with open(os.path.join(dirname, txt_in)) as infile:
        # do stuff with infile
        ...