笨办法学Python 习题17

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()

结果报错
在这里插入图片描述
网上解决办法

  1. 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
  2. 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出现的是以下结果
在这里插入图片描述
我不知道咋办了。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值