python 笔记 文件内容的拷贝 (《笨办法学Python》习题17)——12.26

习题 17:更多文件操作

目标与感悟:

 

•复制文本内容至其他文件中

 

ex17.py

#-*-coding: utf-8-*-
from sys import argv
 
'''
此处引用了新的内置函数,exists函数是检查括号内字符串所代表的文件名的文件是否存在,
存在返回True,不存在返回False。
os.path os.path模块主要用于文件的属性获取,在编程中经常用到
'''
from os.path import exists
 
script, from_file,to_file = argv
 
print "Copying from %s to %s" % (from_file, to_file)
 
# we could do these two on one line too, how?
in_file = open(from_file)
indata = in_file.read()
 
#len(),则是用于传递字符串的长度。
print "The input file is %d bytes long" %len(indata)
 
#此处使用exists验证新文件是否已经存在。
print"Does the output file exist? %r" % exists(to_file)
print"Ready, hit RETURN to continue,CTRL-C to abort."
 
#此处的raw_input()我还是不是特别理解,只知道大概是询问下一步是否继续。稍后做个简化测试。
raw_input()
 
#将open函数得到的结果(是一个文件,而不是文件的内容)赋值给in_file。
out_file = open(to_file, 'w')
 
#使用read函数读取文件内容,并将文件内容赋值给indata。
out_file.write(indata)
 
print "Alright, all done."
 
#最后保存关闭。
out_file.close()
in_file.close()


运行结果:

•很明显看出不同来了,对比2次运行结果,通过exists(to_file)来进行了一次判定,因为第一次运行时候文件不存在,所以第一次是false,第二次是true



感悟与自我测试:

自己参照原文,简化写个脚本吧。

ex17_1.py

#-*-coding:utf-8-*-
from sys import argv
from os.path import exists
 
script, from_file,to_file = argv
 
print"Copy,from %r to %r" %(from_file,to_file)
 
in_file = open(from_file)
read_file = in_file.read()
 
print "%d" %len(read_file)
print "Is exist? %r" %exists(to_file)
 
raw_input("Continue?")
 
out_file = open(to_file,'w')
out_file.write(read_file)    
 
print "Allright!"
out_file.close()
in_file.close()    
'''
总结下最关键的4个句子:
in_file = open(from_file)
read_file = in_file.read()
out_file = open(to_file,'w')
out_file.write(read_file)
 
翻译过来就是:
打开源文件
读取源文件
打开/新建目标文件
写入目标文件
 
'''

运行结果:




是的,看起来还不够简洁,让我们来个最不友好的简单脚本。

 

ex17_2.py

#-*-coding:utf-8-*-
 
from sys import argv
script, from_file,to_file = argv
 
 
in_file = open(from_file)
read_file = in_file.read()
out_file = open(to_file,'w')

out_file.write(read_file)

运行结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值