显然还有其他关于阅读 .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")
提前致谢!
请您参考如下方法:
readline 的参数不是行的编号,它告诉readline方法最多可以读取多少个字符>。使用 print(file.readline()),而不是 print(file.readline(i))。
否则对于输入 5,会发生这种情况:文件的内容是
1\n2\n3\n4\n5\n
现在,第一次迭代最多读取 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!")
