Search code examples
pythoncsvline

How to remove a range of lines from csv file?


I Would like to remove lines 3 to 15 from file 'Database.csv'. Please see my code below, this code is works only for one line i added range, but is didn't work. ;/

filename = 'Database.csv'
line_to_delete = [3:15]
initial_line = 1
file_lines = {}

with open(filename) as f:
    content = f.readlines()

for line in content:
    file_lines[initial_line] = line.strip()
    initial_line += 1

f = open(filename, "w")
for line_number, line_content in file_lines.items():
    if line_number != line_to_delete:
        f.write('{}\n'.format(line_content))

f.close()
print('Deleted line: {}'.format(line_to_delete))

Solution

  • You can use csv library for doing this.

    import csv
    file=open("Database.csv",'rb')
    final_file=open("Database_edited",'wb')
    writer=csv.writer(final_file)
    line_no=1   # for knowing the line number
    for row in csv.reader(file):
        if(line_no<=3 or line_no>=15):
            writer.writerow(row)
        line_no=line_no+1
    file.close()
    final_file.close()
    

    This way Database_edited will have your required file