ynitSed ynitSed - 1 year ago 97
Python Question

Deleting lines in python

I was just wondering how to delete lines in python.

Firstly I have opened up the csv file (using the with statements and whatnot), however the first couple of lines are unneccessary. They go along the lines of this:

**version 2.0 keyboard strokes

version 1.5 mouse wheel

... ..**

[data starts here which i will manipulate]

Any functions I could use to perheps prompt the user with the number of rows theyd like to delete for future spreadsheets?

from __future__ import print_funciton
import fileinput
import csv

with open('filename.csv', delimiter=",")

readcsv = csv.reader(csvfile, delimiter=",")
skip_rows = int(input('How many rows to skip? '))

for i in range(skip_rows):
_ = next(readcsv)
for row in readcsv:

Alternatively, I tried this, but it doesnt seem to get rid of the rows that have blank spaces (blank rows included in the number of rows I'd like to delete). Meanwhile, the code above appears to get rid of those blank spaces, but there is line termination.

next(filecsv) for i in range(10)

Answer Source

Use fileinput.input() with the inplace update file option:

from __future__ import print_function
import fileinput

skip_rows = int(input('How many rows to skip? '))
f = fileinput.input('input.csv', inplace=True)
for i in range(skip_rows):
for row in f:
    print(row, end='')

This will skip the first skip_rows rows of the input file and overwrite it without you having to manage writing and moving a temporary file.

(You can omit importing print_function if you are using Python 3)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download