使用Python读取文本文件没有返回任何内容。

huangapple go评论72阅读模式
英文:

reading a text file with python return nothing

问题

这个 print(file.read()) 代码可以正常工作,它返回整个内容。但是,当我尝试以列表的形式返回内容时使用 print(file.readlines()),它返回一个空列表 []。

我的调试是这样的,我尝试使用 len(file.readlines()) 来确保它确实返回了空列表,它的确是如此。它打印出0。

英文:

I have a text file with some content, I need to return that content in order to print it and some update
I used the absolute path to be sure the path is correct

file = open(r'path\to\file.txt','r')

This print(file.read()) works fine, it returns the whole content. But when i try to return the content in a form of list using print(file.readlines()) , it returns nothing; an empty list [].

my debugging was like this, I tried len(file.readlines()) to make sure, it is indeed returning nothing, and it does. It prints 0

答案1

得分: 0

关键在于文件指针。在读取内容后,file.read() 会将指针设置在内容的末尾。

  • 解决方案 1(不良实践):在每次操作后打开和关闭文件 file.close(),然后 open(r'path\to\file.txt','r')

  • 解决方案 2:更改文件指针

    file.seek(0) # 0 将指针设置在开头,然后使用 print((file.readlines()))

英文:

the key here is file pointer
file.read() after reading the content it sets the pointer at the end of your content.

  • solution 1(bad practice) : open and close after every action file.close() then opren(r'path\to\file.txt','r')

  • solution 2: change the file pointer

    file.seek(0) # 0 will set the pointer at the start,then use print((file.readlines()))

答案2

得分: -1

以下是翻译好的部分:

filename = "this/is/a/file"

with open(filename, "r") as file:
   lines_list = file.readlines()

print(lines_list)

只是以防你不知道,当使用 with 时,你不需要手动关闭文件。这就是为什么上面的示例没有包括关闭文件。

此外,根据 Ayb009 的回答,似乎你尝试在不关闭文件的情况下再次读取文件,这会从上次读取的最后一个字符的下一个字符开始。这里的解决方案完全避免了这个问题,让你可以在不需要保持文件打开的情况下随意处理行。

英文:

So it should look something like this::

filename = "this/is/a/file"

with open(filename, "r") as file:
   lines_list = file.read_lines()

print(lines_list)

Just in case you don't know, you don't need to manually close the file when you use with. So that's why it's missing above.

Also, based on Ayb009's answer it just seems like you tried to read again without closing the file which would start from the last character read + 1. The solution here skips that issue entirely by letting you do whatever you want with the lines without needing to keep the file open.

huangapple
  • 本文由 发表于 2023年3月12日 06:42:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75710028.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定