笨方法学python:习题 17: 更多文件操作(python3)

编写一个 Python 脚本,将一个文件中的内容拷贝到另外一个文件中。

这个脚本很短,不过它会让你对于文件操作有更多的了解。

笨方法学python:习题 17: 更多文件操作(python3)

 #导入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)

print("Alright,all done.")
#关闭文件(保存到硬盘)
out_put.close()
in_put.close()

习题3:. 看看你能把这个脚本改多短,我可以把它写成一行。

代码简化:

from sys import argv 
script, from_file, to_file = argv 
# 读取源文件信息 
indata = open(from_file).read() 
# 写入文件信息 
open(to_file, 'w').write(indata) 


#或


from sys import argv
script, from_file, to_file = argv
#读取后写入文件信息
open(to_file, 'w').write(open(from_file).read())


习题6:找出为什么你需要在代码中写 output.close() 。

关闭文件才能保存到硬盘;