1 from sys import argv
 2 from os.path import exists
 3 
 4 script, from_file, to_file = argv
 5 
 6 print("Copying from %s to %s" % (from_file, to_file))
 7 
 8 # open 打开只读文本
 9 input_file = open(from_file)  # Python3.x 不要用input做变量名,变量名变更后,下方使用到的地方也要跟随改变
10 # read读取文本
11 indata = input_file.read()
12 
13 print("输入的文件长度为:%d" % len(indata))
14 
15 print("输出的文件是否存在?%r" % exists(to_file))
16 print("点击回车Enter继续下一步")
17 input()
18 
19 # 加‘w',以可写权限打开文本
20 output = open(to_file, 'w')
21 # 写入已读取的文本
22 output.write(indata)
23 
24 print("完成复制")
25 
26 output.close()
27 input_file.close()

加分习题,缩短代码,分两部完成,理解最终实现一行代码
第一步:
b = open(from_file)
# 读,可以直接默认读取已打开的文本
c = b.read()      # 这里把read分开写为什么报错??,要再定义一个变量
a = open(to_file, 'w')
# 写,必须要给出要写入的参数
a.write(c)

第二步:

open(to_file, 'w').write(open(from_file).read())

 

 

关于open的详细解释:

因为默认open只能读取不能写入,所以要写入内容就必须加入’w’参数。

‘w’:以只写模式打开。若文件存在,则会自动清空文件,然后重新创建;若文件不存在,则新建文件。使用这个模式必须要保证文件所在目录存在,文件可以不存在。该模式下不能使用read*()方法

 



 

 

 

posted on 2018-07-08 22:47  你猜我猜你猜我猜不猜  阅读(1130)  评论(0编辑  收藏  举报