我正在尝试读取日志文件。它使用记事本作为 txt 文件打开。但是,当我尝试使用 python 读取文件时,它无法打开

I am trying to read a log file. It opens using notepad as txt file. However when I try using python to read the file it doesn't open

这是我在尝试读取文件时遇到的错误。

 logfile = open(r'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.txt')

IOError: [Errno 2] No such file or directory: 'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.txt'


logfile = open(r'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.log')



with open(logfile, 'r') as read:
TypeError: coercing to Unicode: need string or buffer, file found

如您所见,当我尝试读取 txt 文件时,它无法识别该文件。当我尝试读取日志文件时,它找到了该文件但生成错误。

关于如何读入此文件的任何建议。它是一个简单的文本文件,包含这样的行

[02/Jan/2015:08:07:32] "GET /click?article_id=162&user_id=5475 HTTP/1.1" 200 4352

我已经尝试将文件名更改为 txt,但没有用。

错误一:文件
r'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.txt'
不存在。 错误二: 文件
'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.log'
确实存在,但函数 open(...) 需要一个字符串,该字符串是文件的完整路径。在 with open(logfile, 'r') as read: 行中,变量 logfile 已经是一个文件对象,不再是字符串。 尝试以下操作:

logFilePath = r'C:/Users/AmitSingh/Desktop/Data/data_scientist_test/access_log/access.log'
with open(logFilePath, 'r') as fileObject:
    pass # do the stuff you want with the file
    # When you leave this indentation, the file object will be closed again