学习 Python 困难的方法 argv 和文件

learning Python the hard way argv and file

我正在学习 python 过去几周的经验

from sys import argv
script,filename = argv 
print "We're delete the file %r" %filename
print "If you want to stop ctrl+c (^c)"
print "Please hit enter to continue"
raw_input(">_")
print "Opening file..."
filen = open(filename,'w')
print "Truncating your file...."
filen.truncate()
print "now in your file %r" %filen
print "Writing time write  something to your file"

line = raw_input("?")
print "write in progress..."
filen.write(line)
filen.write("\n end of document\n")
filen.close()

我想查看文件的内容,但是当我使用 print filenameprint filen 时,它显示名称并在变量 filen

上打开文件

您可以使用 filen.read()filen.readline()filen.readlines()

读取数据

1) 阅读

fo = open(filename,read)
fo.seek(0, 0) #seek is used to change the file position.This requires only for read method
fo.read(10) #This reads 1st 10 characters
fo.close()

2) 阅读行

fo = open(filename,read)
fo.readline() #This will read a single line from the file. You can add for loop to iterate all the data
fo.close()

3) 阅读线。

fo = open(filename,read)
fo.readline() #read all the lines of a file in a list 
fo.close()

下面的文档会给你更好的主意。 https://docs.python.org/2/tutorial/inputoutput.html

如果要打印打开文件的内容,只需使用:print filen.read().

最简单的:

from sys import argv
script,filename = argv 
with open(filename) as f:
    print f.readlines()

转储文件内容 或:

from sys import argv
script,filename = argv 
with open(filename) as f:
    lines=f.readlines()
for line in lines:
    print line

1 乘 1 打印行