先上代码:
from sys import argv
script, filename = argv
f = open(filename)
f.seek(6)
print f.readline()
print f.readline()
print f.readline()
然后是txt文件:
12345
abcdef
3333333
44444444
最后是powershell里显示的:
abcdef
3333333
求问为什么读不出最后一行来
如果将seek(6)改成seek(0)就不会出现这种情况
First let’s talk about the conclusion .
The
print f.readline()
of your fifth line of code prints out the newline charactern
. If you want to print out the last line of text, you can have two Method:print f.readline()
打印出了换行符n
,如果想打印出文本的最后一行,可以有两个方法:加一行
print f.readline()
将
f.seek(6)
中的数值改为7我想说我是如何解决这个问题的。
我复制了你的代码(进行了些微改动),然后运行,你说的情况出现了:没有打印出最后一行。
于是我想知道发生了什么,开始进行一个个排除。
首先,我删除了最后一行代码(第八行的
print f.readline()
),发现打印的内容少了一行。从而确定,不是最后一行没打印文本,而是前面的两个print f.readline()
之一没有打印文本。通过再删除第七行的print f.readline()
确认问题:第六行的代码没有输出想要的文本。其结果如下:就是一行空白。
然后,我开始查看:打印出来的是字符串类型吗?通过
isinstance(..., str)
Add a line
print f.readline()
Change the value in
f.seek(6)
to 7did not print out the last line
.print f.readline()
on the eighth line) and found that the printed content was missing one line. This confirms that it is not that the last line did not print text, but that one of the first twoprint f.readline()
did not print text. Confirm the problem by deleting theprint f.readline()
on the seventh line:isinstance(..., str)
.Then, I guess: is it printing
invisible characters #🎜🎜# (such as line feed, page feed, etc.). So through the code: #🎜🎜# #🎜🎜#Convert it to a list and print it out. Get the result: it prints a newline character. #🎜🎜# #🎜🎜# #🎜🎜#The problem can be solved now. If this kind of problem occurs in the future, you can use the following methods to solve it: #🎜🎜# #🎜🎜# #🎜🎜##🎜🎜#Single-step debugging: You can refer to the tutorial debugging#🎜🎜##🎜🎜# #🎜🎜##🎜🎜#Add or delete codes yourself to view the results#🎜🎜##🎜🎜# #🎜🎜##🎜🎜# If you have done everything but still can’t solve the problem, you can post the process to the Q&A community (such as here), and others may be able to help you solve it~#🎜🎜##🎜🎜# #🎜🎜# #🎜🎜# #🎜🎜#If you read this, you are considered strong, I will only say this, goodbye~#🎜🎜#