ex15~ex16文件操作

2016-03-10  本文已影响38人  果三代

进入文件操作部分,这里涉及文件操作的一些方法,先罗列在下面:

ex15

#coding=utf-8
from sys import argv
script, filename = argv #参数解包到两个变量script, filename

txt = open(filename) #打开filename文件,文件对象

print "Here's your file %r:" % filename
print txt.read() #读取txt内容
txt.close()

print "Type the filename again:"
file_again =raw_input("> ")

txt_again = open(file_again) #再次打开文件

print txt_again.read() #打印文件内容
txt_again.close()

ex16

#coding=utf-8
from sys import argv

script, filename = argv #filename文件本来没有
                        #命令行直接输入文件名后自动创建新空文档

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 "Opening the file..."
target = open(filename,'w') #以写试打开文件

print "Truncating the file. Goodbye!"
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: ")

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")

print "And finally, we close it."
target.close() #操作完成后关闭文件
上一篇下一篇

猜你喜欢

热点阅读