简体   繁体   English

为什么文件的第一行不打印?

[英]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. 我正在尝试打印n行,并删除每行打印的前4个字符,但是第一行没有显示。

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. 然后,当您调用infile.readlines() ,它从第二行开始。

So get rid of that unnecessary statement. 因此,摆脱不必要的声明。

Also, range(n-1) should be range(n) . 同样, range(n-1)应该是range(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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