我正在尝试使用for循环打印.txt文件的多行.它始终缺少最后三行

1 python for-loop text-files

显然还有其他关于阅读.txt文件的最后一行的问题,但我真的不明白答案,也不知道如何在我的代码中应用它们.

我创建了一个简单的程序,它在.txt文件中写入一系列数字,每个数字都有一个新行.然后您可以选择要打印的数量.

出于某种原因,它错过了最后3行,例如:

  • 我选择在文件上写100个数字
  • 在下一步中,我选择打印n行.
  • 它只打印n-3行!

我可以通过在我想要打印的行数上加3来"解决"这个问题,但那是不对的.我不明白为什么会这样..txt文件中没有任何空行.它实际上只是一个文件,每行一个数字,从头到尾.

代码是这样的:

print("How many numbers to write on file?")
x = input()
x = int(x)

file = open("bla.txt", "w")

for i in range(0,x):
    file.write(str(i))
    file.write("\n")

file.close()

print("How many numbers to print?")

y = input()
y = int(y)

file = open("bla.txt", "r")

for j in range(0,y):
    print(file.readline(j))

file.close()

print("Done!\n")
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Ant*_*ala 5

的说法readline不是数量,它告诉多少个字符readline方法允许读取最多.使用print(file.readline()),而不是print(file.readline(i)).

否则输入5,将发生:文件的内容是

1\n2\n3\n4\n5\n
Run Code Online (Sandbox Code Playgroud)

现在,第一次迭代读取最多0个字符,返回空字符串''.这是用换行符打印的.第二个读取最多1个字符,现在将包含该数字0.这是用换行符打印的.第三次读取最多会读取2个字符,但会立即遇到换行符,并返回只有一个换行符的字符串.这是打印的,带有额外的换行符print.现在读取4将读取最多3个字符,现在将返回'3\n'仅2个字符的字符串.这是打印的,带有额外的换行符.最后,最后一次读取将读取最多4个字符,返回'5\n',再次使用额外的换行符打印.


最后,没有人像那样编写实际的Python代码.请尝试以下方法:

# you can add a prompt to the input itself
num_lines = int(input("How many numbers to write on file? "))

# with will automatically close the file upon exit from the block
with open("bla.txt", "w") as output_file:
    # 0 as start implied
    for i in range(num_lines):
        # print will format the number as a string, a newline is added automatically
        print(i, file=output_file)

num_lines = int(input("How many lines to read? "))    
with open("bla.txt", "r") as input_file:
    # _ is the common name for a throw-away variable 
    for _ in range(num_lines):
        # get the *next* line from file, print it without another newline
        print(next(input_file), end='')

# or to read *all* lines, use
# for line in file:
#     print(line)    

print("Done!")
Run Code Online (Sandbox Code Playgroud)