先上代码
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的文本。