Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

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:

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

How can I make it read the file?

like image 400
F. Taylor Avatar asked Aug 03 '16 12:08

F. Taylor


1 Answers

The open method opens the file and returns a TextIOWrapper object but does not read the files content.

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

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:

with open(P, 'r') as G:
    print(G.read())
like image 139
iCart Avatar answered Oct 28 '22 01:10

iCart