在 Python 中打开一个 .log 扩展文件

rob*_*d91 2 python logfile-analysis readfile logfile

我试图在 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())
Run Code Online (Sandbox Code Playgroud)

追溯:

f  = open('some.log', "r")
IOError: [Errno 2] No such file or directory: 'some.log'
Run Code Online (Sandbox Code Playgroud)

Won*_*ket 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())
Run Code Online (Sandbox Code Playgroud)