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

作者: uranusjr (←這人是超級笨蛋)   2016-03-02 23:35:46
※ 引述《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())
我不確定後面的方法會不會比較快, 但至少比較省記憶體(不用整個檔讀進來)
作者: boGhosts (迷幻停車場。)   2016-03-04 23:27:00
清楚,推一個
作者: gbllggi (gbllggi)   2016-03-05 02:47:00
筆記推
作者: GNUGCC (-std=c++14)   2016-08-10 00:59:00
void main(void) 的寫法是可行的唷^^雖然這個寫法較傳統,但是語法與文法都正確哦^^目前我使用的 Visual C++ 都接受 void main(void) 與int main(void),各位可以把 C++ 專案改成原生 C++ 類型來用 void main(void) 來寫發現也可通過編譯.這個就是 Visual C++ 的彈性.

Links booklink

Contact Us: admin [ a t ] ucptt.com