《笨办法学Python3》练习十七:更多文件操作

练习代码

from sys import argv
from os.path import exists

script, from_file, to_file = argv

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

# we could do these 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()

Study Drills

  1. This script is really annoying. There’s no need to ask you before doing the copy, and it prints too much out to the screen. Try to make the script more friendly to use by removing features.

  2. See how short you can make the script. I could make this one line long.

one line code

from sys import argv
open(argv[2], 'w').write(open(argv[1]).read())
  1. Notice at the end of the What You Should See section I used something called cat? It’s an
    old command that concatenates files together, but mostly it’s just an easy way to print a file to
    the screen. Type man cat to read about it.

cat 命令

  1. Find out why you had to write out_file.close() in the code.

...If you don’t explicitly close a file, Python’s garbage collector will eventually destroy the object and close the open file for you, but the file may stay open for a while. Another risk is that different Python implementations will do this clean-up at different times...(摘自官方文档)

还有一个更常用的办法,且不用手动close

# 使用 with 语句打开文件,with语句执行完毕后自动close
with open(filename) as f:
    content = f.read()
f.closed # True
  1. Go read up on Python’s import statement, and start python3.6 to try it out. Try importing
    some things and see if you can get it right. It’s alright if you do not.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容