我有一个文件,想在Python中打开它,使用以下代码:
f = open("C:/data/lastfm-dataset-360k/test_data.tsv", "r", "utf-8")
调用此代码会导致错误
TypeError:需要整数
除了这一行代码,我已经删除了所有其他代码,但仍然出现错误。我做错了什么,如何正确打开它?
根据open()
的文档:
open(name[, mode[, buffering]])
[...]
可选的缓冲参数指定文件的期望缓冲大小:0表示无缓冲,1表示行缓冲,任何其他正值表示使用大约那个大小的缓冲区。负缓冲意味着使用系统默认值,通常对于tty设备是行缓冲,对于其他文件是完全缓冲。如果省略,则使用系统默认值。
你似乎在尝试将描述文件编码方式的字符串作为第三个参数传递给open()
。请不要这样做。
你使用了错误的 open 函数。
>>> help(open)
Help on built-in function open in module __builtin__:
open(...)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object. This is the
preferred way to open a file. See file.__doc__ for further information.
正如你所看到的,它期望缓冲参数是一个整数。
你可能想要的是codecs.open:
open(filename, mode='rb', encoding=None, errors='strict', buffering=1)
从帮助文档中得知:
open(...)
open(file, mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True) -> file object
encoding='utf-8'
;Python认为你正在传递缓冲区参数。 with open('tomorrow.txt', mode='w', encoding='UTF-8', errors='strict', buffering=1) as file:
file.write(result)
open
的最后一个参数是缓冲区的大小,而不是文件的编码。
文件流更多或少与编码无关(除了在非二进制模式下打开的文件上进行换行符转换),您应该在其他地方处理编码(例如,当您使用 read()
调用获取数据时,可以使用其 decode
方法将其解释为 utf-8
)。
f = open(...)
这一行,还是在 Python 核心库中? - ninjagecko