Python giving FileNotFoundError for file name returned by os.listdir

天涯浪子 提交于 2019-11-26 16:47:49
Antti Haapala

It is because os.listdir does not return the full path to the file, only the filename part; that is 'foo.txt', when open would want 'E:/somedir/foo.txt' because the file does not exist in the current directory.

Use os.path.join to prepend the directory to your filename:

path = r'E:/somedir'

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

(Also, you are not closing the file; the with block will take care of it automatically).

os.listdir(directory) returns a list of file names in directory. So unless directory is your current working directory, you need to join those file names with the actual directory to get a proper absolute path:

for filename in os.listdir(path):
    filepath = os.path.join(path, filename)
    f = open(filepath,'r')
    raw = f.read()
    # ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!