我很擅长编程(显然)和一般的高级计算机.我只有基本的计算机知识,所以我决定要学习更多知识.因此,我正在自学(通过视频和电子书)如何编程.
无论如何,我正在编写一段代码,打开一个文件,在屏幕上打印出内容,询问你是否要编辑/删除/等内容,这样做,然后重新打印结果并要求您确认保存.
我坚持打印文件的内容.我不知道用什么命令来做这件事.我之前尝试过键入几个命令,但这是我尝试过的最新版本,但代码不完整:
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)
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)
这将在终端中打印文件.
with open("filename.txt", "w+") as file:
for line in file:
print line
Run Code Online (Sandbox Code Playgroud)
该语句会自动为您打开和关闭它,您可以使用简单的循环with迭代文件的行for
| 归档时间: |
|
| 查看次数: |
83470 次 |
| 最近记录: |