Exercise 15
代码
from sys import argv
script, filename = argv
txt = open(filename)
print "Here is your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
输出
Notes:
①查看python文档,python提示打开文件的首选方法是open(name[,mode[,buffering]])函数
②文件对象.read()方法读取文件内容,有一个可选参数选择读取的长度,语法为file.read([size])
③在python的交互模式中打开文件,需输入文件的完整目录
>>> txt = open("E:\\code\\LPTHW\\ex15_sample.txt")
>>> print txt.read()
One
Two
Three
④文件对象.close()用于保存并关闭文件,在对文件操作完成后关闭文件
Exercise 16
代码
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."
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("Line 1: ")
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")
print "And finally, we close it."
target.close()
输出
Notes:
①文件对象.truncate()方法会清除文件内容
②write()方法把括号中的字符串对象写入文件中,字符串对象支持格式化及转义操作
③open()打开模式'w'表示也写的方式打开,文件不存在会被创建,已存在会在打开时清空内容。不添加打开参数时,open()默认以只读的方式打开文件
Exercise 17
代码
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file,to_file)
# we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
out_file = open(to_file,"w")
out_file.write(indata)
print "Alright, all done."
out_file.close()
in_file.close()
输出
Notes:
①os.path模块中的exists()函数用来判断一个文件是否存在,存在返回True,否则返回False