本章学习重点:

  • 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.
最后修改:2021 年 03 月 16 日
如果觉得我的文章对你有用,请随意赞赏