相关疑难解决方法(0)

我什么时候应该使用file.read()或file.readlines()?

我注意到如果我遍历我打开的文件,迭代它而不"读取"它会快得多.

l = open('file','r')
for line in l:
    pass (or code)
Run Code Online (Sandbox Code Playgroud)

比...快得多

l = open('file','r')
for line in l.read() / l.readlines():
    pass (or code)
Run Code Online (Sandbox Code Playgroud)

第二个循环将花费大约1.5倍的时间(我在完全相同的文件上使用timeit,结果是0.442对0.660),并且会得到相同的结果.

那么 - 我什么时候应该使用.read()或.readlines()?

因为我总是需要迭代我正在阅读的文件,并且在经过艰难的学习之后,.read()对大数据的缓慢感觉 - 我似乎无法想象再次使用它.

python io timeit

20
推荐指数
1
解决办法
4万
查看次数

如何读取中文txt文件(Python)

我有一个名为“chinchars.txt”的 .txt 文件。在里面,我有一行包含这两个字符:

\n\n

\xe8\x8a\x82\xe6\x97\xa5

\n\n

我如何读取这个文本文件并将其返回给字符?\n使用此代码:

\n\n
inputFile = open(\'chinchars.txt\').readlines()\n
Run Code Online (Sandbox Code Playgroud)\n\n

它输出这个错误:

\n\n
UnicodeDecodeError: \'charmap\' codec can\'t decode byte 0x8f in position \n18: character maps to <undefined>\n
Run Code Online (Sandbox Code Playgroud)\n\n

我相信我需要以某种方式“解码”这些字符。这将如何实现?

\n

python decode file utf-8 python-3.x

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×2

decode ×1

file ×1

io ×1

python-3.x ×1

timeit ×1

utf-8 ×1