ex17 更多文件操作

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() 方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值