python - 为什么使用seek()后readline()读取不了最后一行
黄舟
黄舟 2017-04-17 17:14:14
0
1
610

先上代码:

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)就不会出现这种情况

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
巴扎黑

First let’s talk about the conclusion .

The print f.readline() of your fifth line of code prints out the newline character n. 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 7


I want to say how I solved this problem.
  1. I copied your code (with slight changes) and then ran it. The situation you mentioned occurred:

    did not print out the last line

    .
  2. So I wanted to know what happened and started to rule it out one by one.

    First, I deleted the last line of code (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 two print f.readline() did not print text. Confirm the problem by deleting the print f.readline() on the seventh line:
  3. The code on the sixth line does not output the desired text
  4. . The result is as follows:

    is just a blank line.
Then, I started to check: Is the printed string type? Confirm that it is a string through isinstance(..., str).

Then, I guess: is it printing

invisible characters #🎜🎜# (such as line feed, page feed, etc.). So through the code: #🎜🎜#
print list(f.readline())
#🎜🎜#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~#🎜🎜#
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!