需要记住的常用命令:
close -- 关闭文件,相当于编辑器中的File->Save
read -- 读取文件内容分配给一个变量
readline -- 读取一行内容
truncate -- 清空文件,小心使用这个命
write(stuff) -- 写入文件。
python open 使用方法
f=open('/tmp/hello','w')
#open(路径+文件名,读写模式)
#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.
常用模式如:'rb','wb','r+b'等等
读写模式的类型有:
rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
w 以写方式打开,
a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+ 以读写模式打开
w+ 以读写模式打开 (参见 w )
a+ 以读写模式打开 (参见 a )
rb 以二进制读模式打开
wb 以二进制写模式打开 (参见 w )
ab 以二进制追加模式打开 (参见 a )
rb+ 以二进制读写模式打开 (参见 r+ )
wb+ 以二进制读写模式打开 (参见 w+ )
ab+ 以二进制读写模式打开 (参见 a+ )
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally, we close it."
target.close()
target.close()
3. 上面的代码有很多重复,想办法只使用一个target.write()代替上面的6行。
lines = "%s\n%s\n%s\n" % (line1, line2, line3)
target.write(lines)
from sys import argv
script, filename=argv
script, filename=argv
print "We're going to erase %r."% filename
print "If you don't want that, hit CTRL-C."
print "If you do want that, hit RETURN."
raw_input("?")
print "If you don't want that, hit CTRL-C."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target=open(filename, 'w')
target.truncate()
print "Now I'm going to ask you for three lines."
target=open(filename, 'w')
target.truncate()
print "Now I'm going to ask you for three lines."
line1=raw_input("line1:")
line2=raw_input("line2:")
line3=raw_input("line3:")
line2=raw_input("line2:")
line3=raw_input("line3:")
print "I'm going to write these to the file."
lines = "%s\n%s\n%s\n" % (line1, line2, line3)
target.write(lines)
target.write(lines)
target.write("%s\n%s\n%s\n") %(line1, line2, line3)
print"And finally, we close it."
target.close()
print"And finally, we close it."
target.close()