exercise 17

作者: 不娶名字 | 来源:发表于2018-01-01 15:13 被阅读0次
from sys import argv
from os.path import exists

script, from_file, to_file = argv

print(f"Copying from {from_file} to {to_file}")

# we could do thest two on one line, how?
in_file = open(from_file)
indata = in_file.read()

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')
out_file.write(indata)

print("Alright, all done.")

out_file.close()
in_file.close()

练习

from sys import argv
script, from_file, to_file = argv
# 这个程序不能用close(),因为没有变量去引用文件对象,解释器会去侦测到打开的文件,自动关闭它。
# 当执行完这一行的时候,文件自动就被关闭了。
open(to_file,'w').write(open(from_file,'r').read())

4.不关闭文件,它会直到程序结束为止一直占用系统资源
点我有惊喜

资料1
资料2

exercise15~17小结:
建立文件
打开文件
读取文件
写入文件
关闭文件
点击

相关文章

网友评论

    本文标题:exercise 17

    本文链接:https://www.haomeiwen.com/subject/ssctnxtx.html