《笨办法学Python》习题17:1)更多文件操作--脚本改短;2)cat的替代

1.文章中涉及的脚本

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)

# we could do these two on one line too, how?
in_file = open(from_file)
indata = in_file.read()

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."
raw_input()

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

print "Alright, all done."

out_file.close()
in_file.close()

2.运行结果

#shell中输入
python q.py q1.txt q2.txt # q1文本内容复制到q2
#结果:
Copying from q1.txt to q2.txt
The input file is 9 bytes long
Does the putput file exist?True
Ready,hit RETURN to continue,CTRL-C to abort.
RETURN
Alright,all done.
#shell中输入 
cat q2.txt
#结果:
11
22
33

3.思考题:脚本改多短

from sys import argv#导入模块

script,from_file,to_file=argv#导入参数

with open(from_file) as file1,open(to_file,'w') as file2:
    indata=file1.read()
    file2.write(indata)

4.  WindowsPowerShell ,cat  的替代品--type命令

PS D:\>type q1.txt #打开文件,展示内容
11
22
33
44

<参考文章链接:【Windows】Windows中是否有代替Linux中cat的命令_'Ablaze 的专栏-CSDN博客>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值