2017-02-16 55 views

回答

1

这是你所需要的:

def extract_lines(filename,outputname): 
    l = [] 
    with open(filename,'r') as f: 
     for index,line in enumerate(f): #This iterates the file line by line which is memory efficient in case the csv is huge. 
      if index < 2: #first 2 lines 
       l.append(line) 
     if index > 1: # means the file has at least 3 lines 
      l.append(line) 
    with open(outputname,'w') as f: 
     for line in l: 
      f.write(line) 
+0

惊人的,谢谢! – mbf94

+0

感谢您接受我的回答! –

+0

如果 – Adirio

0

我想你也可以使用bash脚本来实现这一要求。

#!/bin/bash 

for file in $(find . -name '*.txt' -o -name '*.csv') 
do 
    sed -n -e '1,2p' -e '$p' ${file} > "result"${file:(-5)} 
done 

此脚本将搜索所有以txt或csv结尾的文件。它会剪切前两行和最后一行,将这些行存储在一个新文件中。

例如,我有三个名为file1.txt,file2.txt,file3.csv的文件,它会分割每个文件的三行,并分别将它们存储在result1.txt,result2.txt,result3.csv中。

+0

这个问题上没有'bash'标签,所以你的回答不是有效的。 –

1
def get_lines(filename, front=2, rear=1): 
    result = [] 
    with open(filename, 'rb') as f: 
     for i, val in enumerate(f): 
      if i >= front: 
       break 
      result.append(val) 

     back_pos = -2 
     f.seek(back_pos, 2) # jump to the second end byte 

     rear_count = 0 
     while True: 
      if '\n' in f.read(1): 
       rear_count += 1 

      if rear_count >= rear: 
       result.extend(f.readlines()) 
       break 

      back_pos -= 1 
      f.seek(back_pos, 2) 

    return result 

很容易读第一行,但很难读最后一行。 到iter行很慢。