2015-08-14 53 views
-1

我有一個大的文本文件,我想從中讀取特定的行並將它們寫入另一個小文件中。舉例來說,在我的文字Python讀取特定的備用行

line1 
line2 
line3 
line4 
line5 
line6 
line7 
line8 
line9 
line10 
... 

現在我想先讀一號線,4號線,line7,line10 ...,然後2號線,LINE5,line8,...,最後3號線,LINE6,line9 ,. ...所以,我也想把所有三組線分別寫入另外三個小文件中。任何人可以建議如何使用readlines()或其他類似的Python方法?

回答

2

使用%

for index, line in enumerate(my_file.readlines()): 
    if (index + 1) % 3 == 1: # means lines 1, 4 ,7, 10.. 
     # write line to file1 
    elif (index + 1) % 3 == 2: # means lines 2, 5 ,8.. 
     # write line to file2 
    else: # means lines 3, 6, 9 
     # write line to file3 
0
import os 

d = '/home/vivek/t' 
l = os.listdir(d) 

for i in l: 
    p = os.path.join(d, i) 
    if os.path.isfile(p) and i == 'tmp.txt': 

     with open(p, 'r') as f: 
      for index, line in enumerate(f.readlines()): 
       if index % 3 == 0: 
        with open(os.path.join(d, 'store_1.txt'), 'a') as s1: 
         s1.write(line) 
       elif index % 3 == 1: 
        with open(os.path.join(d, 'store_2.txt'), 'a') as s2: 
         s2.write(line) 
       elif index % 3 == 2: 
        with open(os.path.join(d, 'store_3.txt'), 'a') as s3: 
         s3.write(line) 

「d」是所有與程序關聯的文件存在的目錄的絕對路徑。 'tmp.txt'是你的原始文件。