1、将一个文件的内容复制到另外一个文件中
#这个脚本用于将一个文件的内容拷贝到另外一个文件中
from sys import argv
from os.path import exists #exits将文件名字符串作为参数,如果文件存在的话,它将返回 True,否则将返回 False
scripts,from_file,to_file = argv
print("Coping from %s to %s." %(from_file,to_file))
# We could do this on one line
input = open(from_file) #将初始文件from_file打开,内容赋给input变量
indata = input.read() #input变量使用read函数将其内容读取,并赋给新变量indata
print("The input file is %d bytes long." %len(indata)) #使用len计算初始文件的字节长度
print("Does the output file exit? %r" %exists(to_file)) #使用exits判断目的文件to_file是否存在,要确保存在这个文件才能将内容写入
print("Ready? hit Enter to continue,hit Ctrl+C to abort.")
output = open(to_file,'w') #打开目的文件to_file,并启用写入功能,文件的内容赋给变量output
output.write(indata) #将indata的内容写入到output变量中
print("All right,done.")
output.close()
input.close()
脚本运行之前from_file的内容如下,to_file的内容为空
This is a test file named from_file.
脚本运行输出
PS E:\tonyc\Documents\Vs workspace\The Hard Way> python ‘.\ex17(更多操作).py’ .\ex17_from.txt .\ex17_to.txt
Coping from .\ex17_from.txt to .\ex17_to.txt.
The input file is 36 bytes long.
Does the output file exit? True
Ready? hit Enter to continue,hit Ctrl+C to abort.
All right,done.
运行完之后可以发现to_file内容已经写入
PS E:\tonyc\Documents\Vs workspace\The Hard Way> cat .\ex17_to.txt
This is a test file named from_file.
思考
1、为什么你需要在代码中写 output.close()
- 因为使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。