Deleting lines in python
<p>I was just wondering how to delete lines in python.</p>

<p>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:</p>

<p>**version 2.0 keyboard strokes</p>

<p>version 1.5 mouse wheel</p>

<p>...       ..**</p>

<p>[data starts here which i will manipulate]</p>

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

<pre><code>    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:
                 print(row,end='')
</code></pre>

<p>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.</p>

<pre><code>    next(filecsv) for i in range(10)
</code></pre>

<p>Use <a href="https://docs.python.org/3/library/fileinput.html#fileinput.input" rel="nofollow"><code>fileinput.input()</code></a> with the inplace update file option:</p>

<pre><code>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):
    f.readline()
for row in f:
    print(row, end='')
</code></pre>

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

<p>(You can omit importing <code>print_function</code> if you are using Python 3)</p>

python csv