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内容已经写入
思考
1、为什么你需要在代码中写 output.close()
- 因为使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/132501.html