我正试图读取一个日志文件。它以文本文件的形式使用记事本打开。但是,当我尝试使用python读取文件时,它不会打开

2024-06-09 23:17:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

 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文件的形式读取时,它无法识别该文件。当我尝试作为日志文件读取时,它会找到该文件,但会生成一个错误。你知道吗

关于如何在中读取此文件的任何建议。它是一个简单的文本文件,有这样的行

[2015年1月2日:08:07:32]“获取/点击?文章\u id=162和用户\u id=5475 HTTP/1.1“200 4352

我已经试过把文件名改成txt,但没有用。你知道吗


Tags: 文件testtxtlogdataaccess错误open
1条回答
网友
1楼 · 发布于 2024-06-09 23:17:37

错误一:文件
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

相关问题 更多 >