简体   繁体   中英

Reading a text file using python

I have the following code:

readFromFile = open('C:\\Users\\sunka\\Desktop\\exampleFile.txt','r')
readFromFile.readlines()
print(readFromFile)

After running the code, I am getting the following issue

<_io.TextIOWrapper name='C:\\Users\\sunka\\Desktop\\exampleFile.txt' mode='r' encoding='cp1252'>

it's not printing the contents in the file.

Kindly help me to fix this

Your readFromFile variable is a file object, that you can read data from. The readlines function returns array of lines inside that opened file.

So what you want to do is:

with open('C:\Users\sunka\Desktop\exampleFile.txt','r') as file_obj:
    print(file_obj.readlines())

Take a closer look at the docs next time.

You can also try the following :

readFromFile = open('C:\\Users\\sunka\\exampleFile.txt','r')
fh = readFromFile.read()
print(fh)

It prints out all the lines in the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM