2014-10-30 23 views
1

在Python中,我怎麼能文件分割成更小的塊高效? 例如,我有一個文件包含140行。我要拆分的文件到FILE1.TXT,FILE2.TXT,file3.txt。文件1有50行,file2的具有50行和file3的具有休息40行。蟒蛇文件分割成小塊有效

回答

4
chunksize = 50 
fid = 1 
with open('path/to/file') as infile: 
    f = open('file%d.txt' %fid, 'w') 
    for i,line in enumerate(infile): 
     f.write(line) 
     if not i%chunksize: 
      f.close() 
      fid += 1 
      f = open('file%d.txt' %fid, 'w') 
    f.close() 
+0

爲什麼downvote? – inspectorG4dget 2014-11-02 02:46:33