练习代码
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
-
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.
-
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())
- 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.
- 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
- 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.
网友评论