본문 바로가기
파이썬

파이썬 os.listdir에서 반환 된 파일 이름에 대해 FileNotFoundError를 제공하는 Python

by º기록 2020. 11. 29.
반응형

다음과 같은 디렉토리의 파일을 반복하려고했습니다.

import os

path = r'E:/somedir'

for filename in os.listdir(path):
    f = open(filename, 'r')
    ... # process the file

하지만 파이썬은 파일이 존재하더라도 FileNotFoundError 를 던졌습니다.

Traceback (most recent call last):
  File "E:/ADMTM/TestT.py", line 6, in <module>
    f = open(filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'foo.txt'

그래서 여기서 무엇이 잘못 되었습니까?

 

해결 방법

 



path = r'E:/somedir'

for filename in os.listdir(path):
    with open(os.path.join(path, filename)) as f:
        ... # process the file

(또한 파일을 닫는 것이 아닙니다. with 블록이 자동으로 처리합니다).

 

참조 페이지 https://stackoverflow.com/questions/28799353

 

 

반응형

댓글