2

我正在尝试在 Python 中打开一个 .log 扩展文件,但我一直遇到 IOError。我想知道这是否与扩展有关,因为显然,进入该循环的唯一方法是目录中是否存在“some.log”。

location = '/Users/username/Downloads'

for filename in os.listdir(location):
    if filename == 'some.log':
       f  = open('some.log', "r")
       print (f.read())

追溯:

f  = open('some.log', "r")
IOError: [Errno 2] No such file or directory: 'some.log'
4

1 回答 1

5

尝试打开不同目录中的文件时,您需要提供绝对文件路径。否则,它会尝试打开当前目录中的文件。

您可以使用os.path.join连接locationfilename

import os

location = '/Users/username/Downloads'
for filename in os.listdir(location):
    if filename == 'some.log':
       f  = open(os.path.join(location, 'some.log'), "r")
       print (f.read())
于 2015-11-20T17:06:33.590 回答