如何在 Python 中打印 .txt 文件的内容? [英] How do I print the content of a .txt file in Python?

查看:54
本文介绍了如何在 Python 中打印 .txt 文件的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm very new to programming (obviously) and really advanced computer stuff in general. I've only have basic computer knowledge, so I decided I wanted to learn more. Thus I'm teaching myself (through videos and ebooks) how to program.

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

Anyways, I'm working on a piece of code that will open a file, print out the contents on the screen, ask you if you want to edit/delete/etc the contents, do it, and then re-print out the results and ask you for confirmation to save.

我一直在打印文件的内容.我不知道使用什么命令来执行此操作.我之前尝试过输入几个命令,但这是我尝试过的最新命令,没有代码不完整:

I'm stuck at the printing the contents of the file. I don't know what command to use to do this. I've tried typing in several commands previously but here is the latest I've tried and no the code isn't complete:

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?"

我正在尝试编写这些练习代码,以包含迄今为止我所学到的尽可能多的内容.另外,如果有什么不同的话,我正在使用 Ubuntu 13.04 和 Python 2.7.4.感谢您到目前为止的任何帮助:)

I'm trying to write these practice codes to include as much as I've learned thus far. Also I'm working on Ubuntu 13.04 and Python 2.7.4 if that makes any difference. Thanks for any help thus far :)

推荐答案

在 python 中打开文件进行阅读很容易:

Opening a file in python for reading is easy:

f = open('example.txt', 'r')

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

To get everything in the file, just use read()

file_contents = f.read()

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

And to print the contents, just do:

print (file_contents)

完成后不要忘记关闭文件.

Don't forget to close the file when you're done.

f.close()

这篇关于如何在 Python 中打印 .txt 文件的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆