一次、多次与任意行写入
1. 先读后写,逐行输入,同样是先open()再read(),
'r':(read)只读,'w':(write)写,'a':(append)追加。
参考: 习题—16
http://www.2cto.com/shouce/Pythonbbf/index.html
# coding: utf-8 # 声明解码方式是utf-8
def write():
print ">>>Open the file..."
filename = raw_input("name: ")
txt = open(path, 'r') # 只读和追加不清空原文件
print txt.read() # path是指文件所在的路径。比如c:\\python27\1.txt
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(line1 + '\n') # 加个换行符 '\n'
txt.write(line2 + '\n')
txt.write(line3 + '\n')
txt.close() # 有开就有关哦!
write()
如果是以“w”写的形式打开的话会清空原有内容。
'r', 'w', 'a'三者均是默认不换行的。
--------------------------------------------------------------------------
2. 多次写入, 每次写入三行(蓝色的也可忽略,可以只用w+的形式打开)
# coding: utf-8
# 是否清空原文件
print "----------If clean the file? Choose yes/y or no/n.----------"
option = raw_input('>>> ')
if 'y' in option:
print "..........File is cleaning.........."
txt = open('721.txt', 'w+') # 用同时读和写的模式打开
# 原文件被清空
elif 'n' in option:
print "..........Ok, we'll append something into file.........."
txt = open('721.txt', 'a+') # 用同时读和追加的模式打开
else:
print '-' * 10 + "Please rechoose" + '-' * 10
option
print "----------Begin to write three lines----------"
Line1 = raw_input("Line 1: ")
Line2 = raw_input("Line 2: ")
Line3 = raw_input("Line 3: ")
txt.write(Line1 + '\n') # 加换行符, 为了使显示更整洁
txt.write(Line2 + '\n')
txt.write(Line3 + '\n')
print "----------File is writing----------"
# 是否继续写入
while True:
print "If continue, please type yes/y or not/n!"
decision =raw_input('>>> ')
if 'y' in decision:
print "----------OK, keep writing----------"
Line1 = raw_input("Line 1: ")
Line2 = raw_input("Line 2: ")
Line3 = raw_input("Line 3: ")
elif 'n' in decision:
print "----------Alright, file is saving.----------"
print "..........And these are what you write.........."
txt.seek(0) # 因为是用w+或a+打印的, 在打印之前得调整指针
print txt.read() # 打印我们写入的内容。看前面的操作是否成功
exit(0) # exit(0) 是正常退出,exit(1)表示发生了错误
txt.write(Line1 + '\n')
txt.write(Line2 + '\n')
txt.write(Line3 + '\n')
else:
print "Please type yes/y or not/n."
txt.close() # 记得关闭打开的文件
r+同a+,是同时追加和读取的模式,不清空原文件。 w+是同时写入和读取的模式,清空原文件。
切记, 调整指针时,seek(0)一定要放在write()之后,read()之前。不然只要用read()还是会
乱码。详情见 http://blog.csdn.net/ztf312/article/details/47259805
------------------------------------------------------------------------------------------------
3. 利用while循环写入任意行, 不过缺点就是无法在代码中打印读取的内容。
# coding: utf-8
print "Now, write down something..."
# 其实按CTRL + Z不过这样就会出现EoF Error。不同的退出方式。
priint "If you want to save and exit, type CTRL + C"
txt = open('path', 'a')
while True:
content = raw_input(">>> ")
txt.write(content + '\n')