【问题标题】:Open a .log extension file in Python在 Python 中打开一个 .log 扩展文件
【发布时间】:2016-02-23 06:22:26
【问题描述】:

我正在尝试在 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'

【问题讨论】:

  • some.log 在工作目录中吗? Tryopen(os.path.join(location, 'some_log'))
  • 像魅力一样工作 - 谢谢!

标签: python readfile logfile logfile-analysis


【解决方案1】:

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

您可以使用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())

【讨论】:

    猜你喜欢
    • 2014-08-03
    • 1970-01-01
    • 2015-01-09
    • 2012-02-25
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    相关资源
    最近更新 更多