如何修复 Python io.TextIOWrapper 错误消息?

问题描述 投票:0回答:2

我知道有几个帖子问了这个问题,我已经尝试了一些解决方案,但我仍然不断收到错误消息。以下两种解决方案都会产生相同的错误消息。我做错了什么?

这是我尝试过的一种解决方案:

def main():
    #Open a file named numbers.txt
    numbers_file = open('numbers.txt','r')

    #read the numbers on the file
    file_contents = numbers_file.read()

    #Close the the numbers file
    numbers_file.close()

    #Print the data that was inside the file
    print(numbers_file)

#Call the main function
main()

这是我尝试过的另一个解决方案:

with open(r"numbers.txt",'r') as numbers_file:
    #read the numbers on the file
    file_contents = numbers_file.read()

    #Close the the numbers file
    numbers_file.close()

    #Print the data that was inside the file
    print(numbers_file)

运行任一程序时收到的错误消息是:

<_io.TextIOWrapper name='numbers.txt' mode='r' encoding='cp1252'>
python
2个回答
3
投票

感谢您的帮助。我意识到我做错了什么。这是我得到的:

def main():
    #Open a file named numbers.txt
    numbers_file = open('numbers.txt','r')

    #read the numbers on the file
    file_contents = numbers_file.read()

    #Close the the numbers file
    numbers_file.close()

    #Print the data that was inside the file
    print(file_contents)

#Call the main function
main()

0
投票

感谢您的回答。

这不是错误消息。 print(numbers_file) 告诉您有关numbers_file 对象的信息。

真的,你必须 打印(文件内容)

© www.soinside.com 2019 - 2024. All rights reserved.