gpt4 book ai didi

python - 保存 readlines 数组需要 RAM 吗?

转载 作者:太空宇宙 更新时间:2023-11-04 00:52:47 26 4
gpt4 key购买 nike

我正在使用 2GB 文件的命令 lineslist = file.readlines()

所以,我猜它会创建一个 2GB 或更大大小的 lineslist 数组。所以,它基本上与 readfile = file.read() 相同,它也创建了 2GB 的 readfile (instance/variable?) ?

为什么在这种情况下我应该更喜欢 readlines?

再加上我还有一个问题,这里也提到了https://docs.python.org/2/tutorial/inputoutput.html :

readline(): a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous;

我不明白最后一点。那么,如果文件末尾没有 \nreadlines() 是否在其数组的最后一个元素中也有明确的值?

我们正在处理组合文件(根据 block 大小拆分)所以,我正在考虑选择 readlines 或 read。由于单个文件在拆分后可能不会以 \n 结尾,并且如果 readlines 返回明确的值,我认为这将是一个问题。)

PS:我没学过python。所以,如果 python 中没有实例之类的东西,或者我在说废话,请原谅我。我只是假设。

编辑:

好的,我刚找到。它不会返回任何明确的输出。

len(lineslist)
6923798
lineslist[6923797]
"\xf4\xe5\xcf1)\xff\x16\x93\xf2\xa3-\....\xab\xbb\xcd"

所以,它不以'\n'结尾。但这不是明确的输出 eiter。

另外,对于最后一行,readline 没有明确的输出。

最佳答案

如果我对您的问题的理解正确,您只是想要组合(即连接)文件。

如果内存通常是一个问题,for line in f 是解决方法。

我尝试使用 1.9GB 的 csv 文件进行基准测试。一种可能的替代方法是读取适合内存的大块数据。

代码:

#read in large chunks - fastest in my test
chunksize = 2**16
with open(fn,'r') as f:
chunk = f.read(chunksize)
while chunk:
chunk = f.read(chunksize)
#1 loop, best of 3: 4.48 s per loop

#read whole file in one go - slowest in my test
with open(fn,'r') as f:
chunk = f.read()
#1 loop, best of 3: 11.7 s per loop

#read file using iterator over each line - most practical for most cases
with open(fn,'r') as f:
for line in f:
s = line
#1 loop, best of 3: 6.74 s per loop

知道了这一点你可以写这样的东西:

with open(outputfile,'w') as fo:
for inputfile in inputfiles: #assuming inputfiles is a list of filepaths
with open(inputfile,'r') as fi:
for chunk in iter(lambda: fi.read(chunksize), ''):
fo.write(fi.read(chunk))
fo.write('\n') #newline between each file(might not be necessary)

关于python - 保存 readlines 数组需要 RAM 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36469680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com