python习题17

 1 from sys import argv
 2 from os.path import exists
 3 
 4 script, from_file, to_file = argv
 5 
 6 print(f"Copying from {from_file} to {to_file}")
 7 
 8 # We could do these two on line ,how?
 9 in_file = open(from_file)
10 indata = in_file.read()
11 
12 print(f"The input file is {len(indata)} bytes long")
13 
14 print(f"Does the output file exist? {exists(to_file)}")
15 print("Ready, hit RETURN to continue, CTRL-C to abort.")
16 input('>>>>')
17 
18 out_file = open(to_file,'w')
19 out_file.write(indata)
20 
21 print("Alright, all done.")
22 
23 out_file.close()
24 in_file.close()

这个脚本没必要在复制之前问你,也没必要在屏幕上输出那么多东西,试着删掉一些特性,让他看起来更友好。

from sys import argv
from os.path import exists
 
script, from_file, to_file = argv

in_file = open(from_file)
indata = in_file.read()
 
out_file = open(to_file,'w')
to_file.write(indata)

print("Alright, all done.")

一行实现

1 from sys import argv
2 
3 script, from_file, to_file = argv
4 
5 open(to_file,'w').write(open(from_file).read())

*为什么要在代码中写out_file.close():关闭文件

posted @ 2018-12-01 17:38  yuriya  阅读(316)  评论(0编辑  收藏  举报