模块名称:测试.py python版本:3 若有错误,敬请指出
#加分习题17
from sys import argv
from os.path import exists
script,from_file,to_file = argv
print("Copying from %s to %s"%(from_file,to_file))
in_file = open(from_file)
indate = in_file.read()
print("The input file is %d bytes long"% len(indate))
print("Does the output file exist? %r" % exists(to_file))#这里不存在,也会创建一个出来
print("Ready,hit RETURN to continue,CTRL-C to abort.")#接上,如果存在,会覆盖之前的内容???
input()
out_file = open(to_file,'w')
out_file.write(indate)
print("Alrifgt,all done.")
out_file.close()
in_file.close()
#1
#2用的是另一种方法
print('---------------------------2')
from sys import argv
from os.path import exists
script,from_file,to_file = argv
print(exists(to_file))
with open(from_file)as f_obj:
a = f_obj.read()
with open(to_file,'w')as f_obj:
f_obj.write(a)
with open(to_file)as f_obj:
b = f_obj.read()
print(b)#打印内容
#3 这里参考了这位博主的,因为我不会=_=http://blog.csdn.net/YxWang12/article/details/77281440
from sys import argv
from os.path import exists
script,from_file,to_file = argv
print(exists(to_file))#若是不需要检查文件是否存在可以省略
open(to_file,'w').write(open(from_file).read())
a = open(to_file).read()#若是不需要查看新文件可以省略
print(a)
#4略
#5略
#6百度的
#close()是为了释放资源。
#如果不close(),那就要等到垃圾回收时,自动释放资源。垃圾回收的时机是不确定的,也无法控制的。
#如果程序是一个命令,很快就执行完了,那么可能影响不大(注意:并不是说就保证没问题)。
#但如果程序是一个服务,或是需要很长时间才能执行完,或者很大并发执行,就可能导致资源被耗尽,也有可能导致死锁
截图1:习题程序运行结果
截图2:加分习题2运行结果(依次为:目录没有该文件,目录有改文件)
截图3:加分习题3