再打开文件时,除了需要制定文件名外,还需要制定一个模式(“r”,”w”,”a”,分别对应于读取、写入、追加)。如果没有制定模式,则应用默认模式”r”。当以写入模式打开文件且该文件尚不存在时,就会创建出一个相应的新文件。
例如,将“Computer Science”放到文件test.txt中:
output_file = open("test.txt","w")
output_file.write("Computer Science")
output_file.close()
一个同时具有读取和写入功能的事例,从输入文件的每一行读取两个数字,在另外一个文件中输出这两个数字以及它们的和。
#test.py
def mysum(input_filename, output_filename):
input_file = open(input_filename,"r")
output_file = open(output_filename,"w")
for line in input_file:
operands = line.split()
sum_value = float(operands[0]) + float(operands[1])
new_line = line.rstrip() + " " + str(sum_value) + "
"
output_file.write(new_line)
output_file.close()
rstrip()
函数用于去掉输入文件每行的换行符。
函数调用:
from test import *
mysum("test.txt", "test2.txt")