Re: [問題] 將list快速寫入檔案的方式?

看板Python作者 (←這人是超級笨蛋)時間9年前 (2016/03/02 23:35), 9年前編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/3 (看更多)
※ 引述《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,
void main(void) 的寫法是可行的唷^^
08/10 00:59

08/10 02:16,
雖然這個寫法較傳統,但是語法與文法都正確哦^^
08/10 02:16

08/10 20:18,
目前我使用的 Visual C++ 都接受 void main(void) 與
08/10 20:18

08/10 20:19,
int main(void),各位可以把 C++ 專案改成原生 C++ 類型來
08/10 20:19

08/10 20:21,
用 void main(void) 來寫發現也可通過編譯.
08/10 20:21

08/11 20:23,
這個就是 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

03/04 23:27, , 1F
清楚,推一個
03/04 23:27, 1F

03/05 02:47, , 2F
筆記推
03/05 02:47, 2F
文章代碼(AID): #1MrmXLv2 (Python)
文章代碼(AID): #1MrmXLv2 (Python)