笨方法学python3 习题17
这里是源代码加注释
from sys import argv
from os.path import exists
#from os
#os.path.exists(path) #这样也可以
prompt = ">_<:" #前缀
script, from_file, to_file = argv #解包
#三种格式化输出格式
#print(f"Copying from /{from_file}/ to /{to_file}/.") #格式化输出
#print("Copying from /{}/ to /{}/.".format(from_file, to_file))
print("Copying from /%s/ to /%s/"%(from_file, to_file))
#we could do these two on one line, how?
in_file = open(from_file) #赋予文件对象
indata = in_file.read() #转化为变量,Python进行变量操作
#格式化输出的三种格式
print(f"The input file is {prompt}{len(indata)} bytes long")
#print("The input file is {} bytes long".format(len(indata)))
#print("The input file is %r bytes long"%(len(indata)))
print(f"Does the output file exist? \n{prompt}: {exists(to_file)}") #exit()函数返回True or False
print("Ready, hit RETURN to continue, CTRL-C to abort.") #给一次机会,可以终止该操作!有些时候是需要的!
input(prompt) #会停下来自动让你选择?
#to_file文件是在命令行参数>>python ex17.py test.txt test03.txt 中创建的,而不是exists()函数如果返回False,然后创建的。exists()函数只看你存不存在
out_file = open(to_file, 'w') #open()写入模式
out_file.write(indata)
print("Alright, all done.")
out_file.close()#最后都要关闭close()
in_file.close()
这里是巩固练习1
from sys import argv
script, from_file, to_file = argv
in_file = open(from_file)
indata = in_file.read()
out_file = open(to_file, 'w')
out_file.write(indata)
out_file.close()
in_file.close()
print("Alright, all done.")
只有import, open(), close()等关键性操作,去掉了安全操作,中间询问要不要继续操作的操作,去掉了查看from_file的字节大小的操作,只留下最后一句:
Alright, all done.
这里是巩固练习2
from sys import argv; script, from_file, to_file = argv; in_file = open(from_file); indata = in_file.read(); out_file = open(to_file, 'w'); out_file.write(indata); out_file.close(); in_file.close(); print("Alright, all done.")
仅仅看后边的提示,在代码中间加个
;
即可把所有的加到一行中去,但影响观感。
笔记
close()函数,在用完文件后确定写入磁盘,而不是在内存中缓冲;
len()函数,以数值的形式返回字符串的长度,如果是txt文件,则open()之后,由文件对象转化为字符串变量。
echo 可以打印一些参数
cat 流文件查看
——by lianfuzhuo