如何在Python中打印.txt文件的内容?

Cou*_*ney 23 python ubuntu

我很擅长编程(显然)和一般的高级计算机.我只有基本的计算机知识,所以我决定要学习更多知识.因此,我正在自学(通过视频和电子书)如何编程.

无论如何,我正在编写一段代码,打开一个文件,在屏幕上打印出内容,询问你是否要编辑/删除/等内容,这样做,然后重新打印结果并要求您确认保存.

我坚持打印文件的内容.我不知道用什么命令来做这件事.我之前尝试过键入几个命令,但这是我尝试过的最新版本,但代码不完整:

from sys import argv

script, filename = argv
print "Who are you?"
name = raw_input()

print "What file are you looking for today?"
file = raw_input()

print (file)

print "Ok then, here's the file you wanted." 

print "Would you like to delete the contents? Yes or No?"
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写这些练习代码,以包含迄今为止我学到的内容.此外,我正在研究Ubuntu 13.04和Python 2.7.4,如果这有任何区别的话.感谢您的帮助到目前为止:)

小智 31

在python中打开文件以便阅读很容易:

f = open('example.txt', 'r')
Run Code Online (Sandbox Code Playgroud)

要获取文件中的所有内容,只需使用read()

file_contents = f.read()
Run Code Online (Sandbox Code Playgroud)

要打印内容,只需执行以下操作:

print (file_contents)
Run Code Online (Sandbox Code Playgroud)

完成后别忘了关闭文件.

f.close()
Run Code Online (Sandbox Code Playgroud)

  • 您应该使用 with 子句,正如其他人在下面的解决方案中提到的那样,因为上下文管理器将负责关闭文件。 (2认同)

iCo*_*dez 28

这样做:

>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
...     print f.read()
Run Code Online (Sandbox Code Playgroud)

这将在终端中打印文件.

  • 这比接受的答案要好. (3认同)
  • 在较新版本的 Python 中,它似乎应该是 `print(f.read())` (2认同)

Ste*_*han 5

with open("filename.txt", "w+") as file:
  for line in file:
    print line
Run Code Online (Sandbox Code Playgroud)

该语句会自动为您打开和关闭它,您可以使用简单的循环with迭代文件的行for