作者uranusjr (←这人是超级笨蛋)
看板Python
标题Re: [问题] 将list快速写入档案的方式?
时间Wed Mar 2 23:35:46 2016
※ 引述《girl5566 (5566520)》之铭言:
: f = open('123.txt','r')
: lines = f.readlines()
: print len(lines) #2000000 lines
: startindex = 30
: endindex = 15000
: outputfile = open('456.txt','w')
: for i in range(startindex,endindex):
: outputfile.write(lines[i])
: outputfile.close()
: 想询问除了这样写以外 有无更快的写法
: 可以直接把string list写到档案内的写法
如果你有仔细看文件, 应该会发现里面有个 writelines method...
https://docs.python.org/2/library/stdtypes.html#file.writelines
startindex = 30
endindex = 15000
with open('456.txt', 'w') as f:
f.writelines(lines[startindex:endindex])
另外如果你确定 input 会是一个档案的话, 也可以直接把两边接起来
with open('123.txt') as fi, open('456.txt', 'w') as fo:
for _ in xrange(startindex): # 跳过 startindex 行
fi.next()
for _ in xrange(endindex - startindex):
fo.write(fi.readline())
我不确定後面的方法会不会比较快, 但至少比较省记忆体(不用整个档读进来)
--
1F:→ GNUGCC:void main(void) 的写法是可行的唷^^08/10 00:59
2F:→ GNUGCC:虽然这个写法较传统,但是语法与文法都正确哦^^08/10 02:16
3F:→ GNUGCC:目前我使用的 Visual C++ 都接受 void main(void) 与 08/10 20:18
4F:→ GNUGCC:int main(void),各位可以把 C++ 专案改成原生 C++ 类型来 08/10 20:19
5F:→ GNUGCC:用 void main(void) 来写发现也可通过编译. 08/10 20:21
6F:→ GNUGCC:这个就是 Visual C++ 的弹性.08/11 20:23
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 101.12.144.19
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1456932949.A.E42.html
※ 编辑: uranusjr (101.12.144.19), 03/02/2016 23:36:09
7F:推 boGhosts: 清楚,推一个 03/04 23:27
8F:推 gbllggi: 笔记推 03/05 02:47