脚本运行内容:
- 系统模块导入参数变量
- 导入 os.path 模块调用 exists 函数
- 解包参数变量(脚本,被复制文件1,粘贴到文件2)
- 打印语句,需要复制文件1内容到文件2
- 打开文件1
- 读取文件1
- 打印 语句,中间用到格式化,len(X) 函数 来运算文件1中字符长度
- 打印 语句,中间用到格式化,exists(Y) 函数 来测试文件2是否存在 结果为True 或 False
- 弹出提示,是否执行复制文件内容,回车或者Ctrl+C
- 用户输入
- 读写方式打开文件2
- 将文件1内容写入文件2
- 关闭文件1文档
- 关闭文件2文档
1 from sys import argv
2 from os.path import exists
3
4 script, from_file, to_file = argv
5
6 print(f"Copying from {from_file} to {to_file}.")
7
8 from_txt = open(from_file) # 打开from_file文件赋值给变量
9 from_txt_read = from_txt.read() # 读取已打开的文件赋值给变量,///注意.read()括号里面不要加东西
10
11 print(f"The input file is {len(from_txt_read)} bytes long.")
12
13 print(f"Do the output {to_file} exist? {exists(to_file)}") # 打印 输出文件是否存在,函数exists()验证该文件名是否存在
14 print("Ready, hit RETURN to continue,CTRL+C to about.") # 打印 准备好按回车键继续,按ctrl+c 中断
15 input(">") # 用户输入选择
16
17 to_txt = open(to_file,'w') # 用写入方式打开to_file文件赋值给变量,注意!!!!'w'需要小写!!!!
18 to_txt.write(from_txt_read) # 将读取的from_txt_read 文本写入变量
19
20 print("Alright,all done.") # 打印 好的,都完成了
21
22 from_txt.close() # 关闭from_txt 文件//注意是文件打开后的变量,而不是真的文件名字
23 to_txt.close() # 关闭to_txt 文件
PS C:\Users\Administrator\lpthw> python ex17.py test.txt test_17.txt
Copying from test.txt to test_17.txt.
The input file is 23 bytes long.
Do the output test_17.txt exist? True
Ready, hit RETURN to continue,CTRL+C to about.
>
Alright,all done.