标签:
先读后写,逐行输入,同样
是先open()再read(),
‘r‘:(read)只读,‘w‘:(write)写,‘a‘:(append)追加。
参考: 习题—16
# coding: utf-8
def write():
print ">>>Open the file..."
filename = raw_input("name: ")
txt = open(filename, ‘r‘) # 只读和追加不清空原文件
print txt.read()
print ">>>Now, we‘ll adding something..."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print ">>>Write three lines into file and eixt..."
txt = open(‘filename‘, ‘a‘) # 在原文件的基础上追加
txt.write("\n") # 以‘a‘形式打开是默认不换行的
txt.write(line1)
txt.write("\n") # 加个换行符 ‘\n‘
txt.write(line2)
txt.write("\n")
txt.write(line3)
txt.close() # 有开就有关哦!
write()
如果是以“w”写的形式打开的话会清空原有内容。
‘r‘, ‘w‘, ‘a‘三者均是默认不换行的。
标签:
原文地址:http://www.cnblogs.com/Ruby517/p/5569698.html