Python glob error <_io.TextIOWrapper name='...' mode='r' encoding='cp1252'> 读取文本文件错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38744244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:23:10  来源:igfitidea点击:

glob error <_io.TextIOWrapper name='...' mode='r' encoding='cp1252'> reading text file error

python

提问by F. Taylor

I am trying to make a social program where the profiles are stored in .txt files here is part of the code:

我正在尝试制作一个社交程序,其中配置文件存储在 .txt 文件中,这是代码的一部分:

XX = []
pl = glob.glob('*.txt')
for a in pl:
     if ' pysocial profile.txt' in a:
         print(a)
         O = 2
         XX.append(a)
         if O == 2:
              P = input('choose profile>')
              if P in XX:
                G = open(P, 'r')
              print(G)

I try this, but when it executes the "print(G)" part it come out with this:

我试试这个,但是当它执行“print(G)”部分时,它会出现:

<_io.TextIOWrapper name='Freddie Taylor pysocial profile.txt' mode='r' encoding='cp1252'>.

<_io.TextIOWrapper name='Freddie Taylor pysocial profile.txt' mode='r' encoding='cp1252'>.

How can I make it read the file?

我怎样才能让它读取文件?

回答by iCart

The openmethod opens the file and returns a TextIOWrapperobject but does not read the files content.

open方法打开文件并返回一个TextIOWrapper对象,但不读取文件内容。

To actually get the content of the file, you need to call the readmethod on that object, like so:

要实际获取文件的内容,您需要调用该read对象上的方法,如下所示:

G = open(P, 'r')
print(G.read())

However, you should take care of closing the file by either calling the closemethod on the file object or using the with open(...)syntax which will ensure the file is properly closed, like so:

但是,您应该通过调用close文件对象上的方法或使用with open(...)确保文件正确关闭的语法来关闭文件,如下所示:

with open(P, 'r') as G:
    print(G.read())