我想使用for chunk in f.chunks()来读取一个巨大的csv文件。它在第一条记录中运行得很好,但是我发现当行到达块的大小时,它会破坏行,因为我知道块的默认大小是64 is。例如,csv文件中有三行:
当我使用for chunk in f.chunks()时,我希望
chunk1包含“这是第一行”,chunk2包含(“这是第二行”,“这是第三行”)或chunk1包含(“这是第一行”,“这是第二行”),chunk2包含(“这是第三行”)
但真正的结果是:
chunk1包含(这是第一行,这是),chunk2包含(‘第二行’,‘这是第三行’)
也就是说,它将把第二行“这是第二行”分割成不同的块。是否有可能防止块破行?谢谢。
发布于 2019-02-26 21:24:21
我也遇到了同样的问题,并发现当您在Django File对象中迭代行时,Django以块的形式读取文件,并且具有“修复”行的逻辑,这些行可能被块边界分割!具体来说,请看一下()方法:
def __iter__(self):
# Iterate over this file-like object by newlines
buffer_ = None
for chunk in self.chunks():
for line in chunk.splitlines(True):
if buffer_:
if endswith_cr(buffer_) and not equals_lf(line):
# Line split after a \r newline; yield buffer_.
yield buffer_
# Continue with line.
else:
# Line either split without a newline (line
# continues after buffer_) or with \r\n
# newline (line == b'\n').
line = buffer_ + line
# buffer_ handled, clear it.
buffer_ = None
# If this is the end of a \n or \r\n line, yield.
if endswith_lf(line):
yield line
else:
buffer_ = line
if buffer_ is not None:
yield buffer_考虑到这一点,只要f是Django File对象,您就可以这样做:
for line in f:
# Do your stuff here
...发布于 2017-08-17 20:33:57
我觉得没那么简单。Django像二进制文件一样管理上传的文件。我建议您不要使用固定长度的块,而是使用f.file对象,并使用readline方法进行迭代。
my_file = f.file
while True:
line = my_file.readline()
if not line:
break
# Do your stuff不太优雅,但很有用
https://stackoverflow.com/questions/43480792
复制相似问题