简体   繁体   English

Python 3.6将文本输出为.txt文件

[英]Python 3.6 printing out the text in a .txt file

Basically I want my python code to be able to read the line I have in my .txt file and print it out in another file when called. 基本上,我希望我的python代码能够读取.txt文件中的行,并在调用时将其打印到另一个文件中。

What I have tried: 我试过的

var = open("Test.txt")
print(var)

I have also tried using readlines(): 我也尝试使用readlines():

var = open("Test.txt")
abcd = var.readlines()
print(abcd)

And what I get when I use that: 当我使用它时,我得到的是:

<_io.TextIOWrapper name='Test.txt' mode='r' encoding='US-ASCII'>

What you are printing is only the object reference of the file and not the actual text within it. 您要打印的只是文件的对象引用,而不是文件中的实际文本。 When printing out the content of a file in python you must use the read() function to return the content of the file. 在python中打印文件内容时,必须使用read()函数返回文件内容。 You should also specify the actions you want to take with the file in the open() function. 您还应该在open()函数中指定要对文件执行的操作。

  • r is read r被读取
  • w is write w是写
  • r+ is read and write r+被读写

For your situation you would use: 对于您的情况,您可以使用:

    var = open('Test.txt', 'r')
    content = var.read()
    print(content) 

This would return the entire content of the file. 这将返回文件的全部内容。

Start with a context manager, what does this get you? 从上下文管理器开始,这对您有什么帮助?

with open('Test.txt', 'r') as f:
    content = f.read()

print (content)

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

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