Re: [問題] 將list快速寫入檔案的方式?
※ 引述《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())
我不確定後面的方法會不會比較快, 但至少比較省記憶體(不用整個檔讀進來)
--
→
08/10 00:59,
08/10 00:59
→
08/10 02:16,
08/10 02:16
→
08/10 20:18,
08/10 20:18
→
08/10 20:19,
08/10 20:19
→
08/10 20:21,
08/10 20:21
→
08/11 20:23,
08/11 20:23
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.12.144.19
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1456932949.A.E42.html
※ 編輯: uranusjr (101.12.144.19), 03/02/2016 23:36:09
推
03/04 23:27, , 1F
03/04 23:27, 1F
推
03/05 02:47, , 2F
03/05 02:47, 2F
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章