简体   繁体   中英

Why is the first line of the file not printing?

I am trying to print n number of lines and take away the first 4 characters for each line printed but the first line is not coming up.

Code:

def saveLine(ifile,ofile,n):
    '''Prints n number of lines with first 4 spaces gone'''
    infile = open(ifile, 'r')
    outfile = open(ofile, 'w')
    line = infile.readline()
    lines = infile.readlines()

    for i in range(n - 1):
        line = lines[i]
        outfile.write(line[4:])
    infile.close()
    outfile.close()

You're skipping the first line because of this:

line = infile.readline()

That reads the first line of the file. Then when you call infile.readlines() , it starts with the second line.

So get rid of that unnecessary statement.

Also, range(n-1) should be range(n) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM