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
glob error <_io.TextIOWrapper name='...' mode='r' encoding='cp1252'> reading text file error
提问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 open
method opens the file and returns a TextIOWrapper
object but does not read the files content.
该open
方法打开文件并返回一个TextIOWrapper
对象,但不读取文件内容。
To actually get the content of the file, you need to call the read
method 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 close
method 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())