Hi all

I have a txt file.

It has a maximum of 24 lines.

E.g.

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
...
Line 24

I would like to delete lines 2, 4, 6 ... 24. All the even numbered lines

this is the code that I have so far

# read the data file in as a list
fin = open( 'sta1214.txt', "r" )
data_list = fin.readlines()
fin.close()
# test first 5 list items ...
print data_list[:5]

print '-'*60

# remove list items from index 2, 4, 6, 8 to 24 (inclusive)
del data_list[0+1]
# test first 5 list items ...
print data_list[:5]

# write the changed data (list) to a file
fout = open("sta1214a.txt", "w")
fout.writelines(data_list)
fout.close()

Thank you

This question was asked already in forum, and I gave answer. Check old posts.

But now I know shorter answer use

lines = open( 'sta1214.txt', "r" ).readlines()[::2]

(every 2 starting from beginning)

and save lines to file.

Edited 6 Years Ago by pyTony: n/a

Hmm -

# -*- coding: utf-8 -*-

_file = open("file.txt", "r")

text = _file.readlines()

for i, j in enumerate(text):
    if i % 2 == 0:
       del text[i]
       
_file.close()

_file = open("file.txt", "w")

for i in text:
    _file.write(i)
    
_file.close()

solved?

Could you, please, mark the discussion solved if you have not further questions?

This question has already been answered. Start a new discussion instead.