简体   繁体   English

使用python读取文本文件

[英]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. 您的readFromFile变量是一个文件对象,您可以从中读取数据。 The readlines function returns array of lines inside that opened file. readlines函数返回该打开文件内的行数组。

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. 它打印出文件中的所有行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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