笨办法学python练习17

先上代码

from sys import argv
from os.path import exists

script,from_file,to_file = argv  # 解包

print("Copying from %s to %s" %(from_file,to_file))  # 打印,从A复制粘粘贴到B

# we could do these two on one line too,how?  # 放在一行中,打开test.TXT改写文件?

input = open(from_file,"w")  # 打开from_file文件的读写模式,w指代txt的内容会被清除
input.write("yes,i want a macbook pro.")  # 写入内容
input.close()  # 关闭文件
input = open(from_file)  # 再次打开,若不关闭,则14行的read无法执行
indata = input.read()  # 将input的内容读到indata变量中
print(indata)  # 打印内容



print("The input file is %d bytes long" % len(indata)) # indata中有多少个字节

print("Does the output file exist? %r" % exists(to_file))  # 看to_file是否存在,若是,回答True,若否,回答False,并创建名名为to_file的txt文件
print("Ready,hit RETURN to continue,CTRL-C to abort.")


output = open(to_file,'w')  # 打开to_file文件
output.write(indata)  # 写入数据

print("Alright,all done.")

output.close()  # 有open必有close
input.close()

注意点1:open的使用方法,简短的说,有三种模式(其实更多,但记不住,有需要的可以去查),分别是
“r”:只读模式,指针放在开头,默认模式
“w”:写入模式,清除原有内容后写入,若无文件可创建
“a”:读写模式,末尾追加内容,若无文件夹可创建

可能有所出入,见谅。
加分题,一行代码写完:

from sys import argv
script,from_file,to_file =argv

open(to_file,"w").write(open(from_file).read()) # write的对象必须是一个打开的文件,即open(from_file,"w")
# open指令打开一个名为txt的文本,若这个文本不存在,则会自动创建名为txt的文本。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值