Avii Avii - 21 days ago 5
Python Question

How to delete text form txt file using python

Suppose a txt file consist of :

1 2 22
4 5 66


how can I delete first line of it . i.e
1 2 22

Answer

You could do it like this:

input_file = open('filename.txt')
output_file = open('output_filename.txt', 'w')
for line in input_file.readlines()[1:]:
    output_file.write(line + '\n')
output_file.close()

Same thing using single file:

input_file = open('filename.txt')
input_data = [line for line in input_file.readlines()]
input_file.close()

output_file = open('filename.txt', 'w')
for line in input_data[1:]:
    output_file.write(line + '\n')
output_file.close()