笨方法学python 习题17

前情提要

exists命令将文件名字符串作为参数,如果文件存在,它将返回True,否则返回False

代码如下

from sys import argv
from os.path import exists

script, from_file, to_file = argv,'from_file','to_file'

print(f'copying from {from_file} to {to_file}')

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

print(f'The input file is {len(indata)} bytes long')

print(f'Does the output file exist?{exists(to_file)}')
print('Ready,hit RETURN to continue,CTRL-C to abort.')
input()

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

print('Already,all done.')

out_file.close()
in_file.close()

结果输出

copying from from_file to to_file
The input file is 0 bytes long
Does the output file exist?False
Ready,hit RETURN to continue,CTRL-C to abort.

Already,all done.

进程已结束,退出代码0

巩固练习

1. 你能把脚本改多短?

from sys import argv

script, from_file, to_file = argv,'from_file','to_file';in_file = open('from_file.txt');indata = in_file.read();out_file = open('to_file.txt','w');out_file.write(indata)
##############
script, from_file, to_file = argv,'from_file','to_file'
cat=('''in_file = open('from_file.txt');indata = in_file.read();out_file = open('to_file.txt','w');out_file.write(indata)''')

2. 'cat’命令是将两个文件拼接(concatenate)到一起,实际用途是打印,通过man cat了解更多的信息

3. 为什么需要在代码写out_file.close()

为了不让代码继续循环

Tips

1. 为什么‘w’要在引号中?

这是一个字符串。

2. 不要把这些放在一行里!

取决于这行代码如何定义。提示:That;depends;on;how;you;define;one;line;of;code.

3. len()函数的功能

以数值的形式返回你传递的字符串的长度。

4. 报错

syntax:EOL white scanning string literal.
#忘记在字符串加引号
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值