файл существует в каталоге, но получает Нет такого файла или каталога: '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'? пожалуйста, помогите. Спасибо!


person Max    schedule 24.05.2020    source источник
comment
следует ли вам выбрать формат для «с открытым (txt_in)», например, «r» или «w»?   -  person Ann Zen    schedule 24.05.2020


Ответы (1)


Проблема в том, что 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
        ...
person Ronald    schedule 24.05.2020