问题描述
我试图获取一个完整的文件到内存(完成 - 使用StringIO) - 但这些对象的行为真的不像真正的文件,只要我看到 - 我得到的全部内容,或我可以一次读取一行,但我无法解决如何应用此模式:
I'm trying to fetch an entire file into memory (done - using StringIO) - but these objects don't really behave exactly like 'real' files as far as I can see - I get the whole contents, or I can read a line at a time, but I can't work out how to apply this pattern:
import csv
with open(#MYMEMORYFILE_HERE#, 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
有一种方法来处理一个内存文件就像一个磁盘文件,所以我可以使用更好的习惯?
Is there a way of treating a memoryfile just like an on-disk file , so I can use the nicer idioms above ?
Python 2.7.4 (default, Apr 19 2013, 18:28:01)
编辑:感谢您的答案 - 我想我已经缩小了什么让我困惑...但我还有一个问题,以下不输出什么?我怀疑刷新?
Thanks for the answers on this - I think I have narrowed down what was confusing me...but I still have an issue here, the following doesn't output anything? I suspect flushing ?
from csv import reader, writer
import StringIO
memfile=StringIO.StringIO()
spamwriter = writer(memfile)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
spamreader=reader(memfile)
for row in spamreader:
print ', '.join(row)
memfile.close()
编辑#2:但我正在咆哮错误的树我想: ('IOError:File not open for reading' - 当我调用已经打开的文件上的读取时...)
编辑#3:放弃StringIO没有真正需要它) - 根据答案使用分割线。
EDIT#2: But I'm barking up the wrong tree I think: I couldn't get the on-disk version of this to work either ('IOError: File not open for reading' - when I call the read on the already open file...)EDIT#3: abandoned the StringIO (no real need for it) - used splitlines as per the answer.
我会在这里留下代码和注释 - 万一有用。 (即使它是一个死胡同)。
I'll leave the code and comments here - in case it's useful. (even though it is a cul-de-sac).
推荐答案
如果你想读取整个文件到内存,它的文本,你不需要打开一个StringIO对象。只需读取它作为一个字符串!
If you want to read a whole file into memory, and it's text, you don't need to open a StringIO object. Just read it as a string!
with open(filename, 'r') as file:
in_memory_file = file.read()
然后您可以使用 splitlines
以迭代方式迭代打开的文本文件。
Then you can use splitlines
to iterate over it the way you would iterate over an open text file.
spamreader = csv.reader(in_memory_file.splitlines(), delimiter=' ', quotechar='|')
for row in spamreader:
pass
这篇关于如何获取CSV读取器读取内存文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!