作者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())
我不確定後面的方法會不會比較快, 但至少比較省記憶體(不用整個檔讀進來)
--
→ GNUGCC:void main(void) 的寫法是可行的唷^^08/10 00:59
→ GNUGCC:雖然這個寫法較傳統,但是語法與文法都正確哦^^08/10 02:16
→ GNUGCC:目前我使用的 Visual C++ 都接受 void main(void) 與 08/10 20:18
→ GNUGCC:int main(void),各位可以把 C++ 專案改成原生 C++ 類型來 08/10 20:19
→ GNUGCC:用 void main(void) 來寫發現也可通過編譯. 08/10 20:21
→ GNUGCC:這個就是 Visual C++ 的彈性.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
推 boGhosts: 清楚,推一個 03/04 23:27
推 gbllggi: 筆記推 03/05 02:47