python - How to remove all lines in a file containing a specific character except for the first? -
i trying make script merges files in directory , remove unwanted lines in output file. lines want remove contain same string pattern , want remove first of lines (which first line in file). here how trying it:
import glob # merge output files 1 file read_files = glob.glob('/home/user/results/script_tests/testresults/*.output') open('mergedoutput.txt', 'r+b') outfile: file in read_files: open(file, 'r+b') infile: outfile.write(infile.read()) print 'files merged.' # remove header rows except row 1 final_output = open('finalmergedoutput.txt', 'r+b') open('mergedoutput.txt', 'r+b') file: line in file: if line == 0 , line.startswith('file'): final_output.write(line) elif line > 0 , not line.startswith('file'): final_output.write(line) print 'headers removed except on line 1.'
the merging part works pretty except lines seem copied in finalmergedoutput.txt
. removal of lines removes lines starting file
, not spare first...
does have elegant solution this?
for line in file
iterates on actual content of file, not line numbers. since empty string greater 0, first condition can never e true , 2nd 1 (when .startswith(..)
true...).
there many idioms of special handling of first item in list, pretty straight forward 1 minimal adjustments code:
for line_num,line in enumerate(file): if line_num == 0 , line.startswith('file'): final_output.write(line) elif line_num > 0 , not line.startswith('file'): final_output.write(line)
Comments
Post a Comment