Python delete certain lines from file -


i have csv file looks following:

ccc, rev, pindex, no. 23, 2.5, 0, 4 34, 4.3, 1, 3 27, 7.9, 2, 5 12, 5.7, 3, 7 

where third element in each line called pindex. have code replicates each line once, while updating pindex accordingly. output looks following:

ccc, rev, pindex, no. 23, 2.5, 0, 4 23, 2.5, 1, 4 34, 4.3, 2, 3 34, 4.3, 3, 3 27, 7.9, 4, 5 27, 7.9, 5, 5 12, 5.7, 6, 7 12, 5.7, 7, 7 

below code that:

with fileinput.input(inplace=true) f:     n = 0     line in f:         line = line.rstrip('\n')         numbers = line.split(sep = ',')         in range(2):             numbers[3] = n             n += 1             s = ''             j in numbers:                 s += str(j) + ','             s = s.rstrip(',')             print(s) 

now want delete 1 duplication each of first , last line, delete first line (after header, pindex 0) , last line in file. using fileinput , trying write result in same file. tried

result = [] result.append(s) 

which makes each line separate array. make array result_all contain lines(as arrays) , result_all[1:-1] rid of first , last line. not seem work well.

any appreciated!

use can iterate in lines , skip line 1 , last line, need know number lines though.

with open('thatfile', 'r') file:    num_of_lines = file.read().count('\n')    file.seek(0)    = 0    open('newfile', 'w') newfile:       line in file:          if != 1 , != num_of_lines:             newfile.write(line)          = + 1 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -