from sys import argv
from os.path import exists#引入os.path模块
# 命令exists 将文件名字符串作为参数,如果文件存在,将返回True;反之返回False
script,from_file,to_file = argv #解包参数,并赋值给变量script,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)# 使from_file的内容打开并赋值到in_file中
indata = in_file.read()# 再将其读取出来
#print(f"The input file is {len(indata) bytes long}")此命令运行时报错,正确命令如下
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')# 以写入为选项open它, 并赋值out_file
out_file.write(indata)# 将out_file写入indata
print("Alright,all done.")
out_file.close()
in_file.close()
结果报错
网上解决办法
- https://blog.csdn.net/qq_37422923/article/details/80204917?utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control
- https://blog.csdn.net/lqzdreamer/article/details/76549256?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control
3.我在本习题中通过一下方法解决该问题
in_file = open(from_file)# 这是习题17中的源代码
in_file = open(from_file,'rb')# 这是修改后的源代码
修改后的运行结果
再次修改
out_file.write(indata)# 原代码
out_file.write(str(indata))# 修改之后的代码
运行结果
(base) PS D:\pythonProject\the_stupid_way_to_learn_python> python ex17.py test.txt new-file.txt
Copying from test.txt to new-file.txt
The input file is 46 bytes long
Does the output file exist? True
Ready,hit RETURN to continue,CTRL-C to abort.
Alright,all done.
终于运行结果和书上一致!!!!
然而打开new-file.txt出现的是以下结果
我不知道咋办了。。。。