本章学习重点:
- 用
echo
创建文件,同时可以用cat
显示文件内容; OS
模块中导入的exists()
作用是判断文件是否存在,存在返回Ture
,否则将返回False
;len()
函数的作用是以数值的形式返回所传递的字符串的长度。
程序代码:
from sys import argv
from os.path import exists
script, form_file, to_file = argv
print(f"Copying from {form_file} to {to_file}")
# we could do these two on one line, how?
in_file = open(form_file)
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, 'w')
out_file.write(indata)
print("Alright,all done.")
out_file.close()
in_file.close()
输出结果:
PS D:\lpthw> python ex17.py test.txt new-file.txt
Copying from test.txt to new-file.txt
The input file is 71 bytes long
Does the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort.
Alright,all done.