编写一个 Python 脚本,将一个文件中的内容拷贝到另外一个文件中。
这个脚本很短,不过它会让你对于文件操作有更多的了解。

#导入sys库的argv参数
from sys import argv
#导入os.path库的exists参数
from os.path import exists
#定义参数变量
script,from_file,to_file=argv
print("Copying from %s to %s" %(from_file,to_file))
#we could do there two on one line too,how?如何把2行写到1行上?
#定义in_put来打开文件;这里in_put加上"_"跟input命令区别起来
in_put=open(from_file)
#定义indata来读取文件
indata=in_put.read()
#打印并用len来计算文件的字符串长度
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.")
input()#输入
#定义out_put为以w写入模式打开目标文件
out_put=open(to_file,'w')
#写入复制的内容
out_put.write(indata

这篇博客介绍了如何使用Python脚本将一个文件的内容复制到另一个文件中,通过实践加深对文件操作的理解。同时提出了挑战,尝试将实现代码简化,并探讨了为何需要调用output.close()来确保文件内容正确保存到硬盘。
最低0.47元/天 解锁文章
263

被折叠的 条评论
为什么被折叠?



