【发布时间】:2013-11-12 04:49:32
【问题描述】:
Bonjour Stack0verflow
我正在尝试获取此代码以将数据写入 stored_output 而无需第 1 行(标题行)
我尝试过的:
with open(filenamex, 'rb') as currentx:
current_data = currentx.read()
## because of my filesize I dont want to go through each line the the route shown below to remove the first line (title row)
for counter, line in enumerate(current_data):
if counter != 0:
data.writeline(line)
#stored_output.writelines(current_data)
由于文件大小我不想做一个 for 循环(效率)
任何建设性的 cmets 或代码 sn-ps 将不胜感激。
感谢 AEA
【问题讨论】:
-
我觉得因为文件比较大,其实循环遍历是个好主意,不然会占满你的内存。
-
另外,按照你的做法,
current_data是一个巨大的字符串,所以enumerate(current_data)给出了每个字符的索引和值,而不是每个线。如果您真的想将整个文件以行的形式读入内存(您可能不会),请执行current_data = currentx.read().splitlines()或者更好的是current_data = list(currentx)。 -
@aIKid 感谢您的评论,我将其存储在内存中。否则我们将执行一个文件写入很多次。内存对我来说不是问题。
-
hcwhsa的回答彻底解决了问题,看看吧。
-
@abarnert 我按顺序打开文件并按顺序附加它们。我不需要以任何方式读取或处理数据。你会建议一种替代方法吗?谢谢
标签: python file python-2.7 stringio