《笨办法学Python3》练习十五:读取文件
练习代码
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here's your file {filename}")
print(txt.read())
print("Type the filename again:")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read())
Study Drills
- Above each line, comment out in English what that line does.
# 从sys模块中导入argv
from sys import argv
# 拆包argv,把其中值对应赋给script,filename变量
script, filename = argv
# 打开文件名为filename的值的文件,将文件流赋给名为txt的变量
txt = open(filename)
# 打印语句,打印文件流内容
print(f"Here's your file {filename}")
print(txt.read())
# 打印语句,提示用户输入新文件名,用file_again存储文件名
print("Type the filename again:")
file_again = input("> ")
# 打开文件,同上
txt_again = open(file_again)
# 打印文件流内容
print(txt_again.read())
-
If you are not sure, ask someone for help or search online. Many times searching for “python3.6 THING” will find answers to what that THING does in Python. Try searching for “python3.6 open.”
-
I used the word “commands” here, but commands are also called “functions” and “methods.” You will learn about functions and methods later in the book.
-
Get rid of lines 10–15 where you use input and run the script again.
-
Use only input and try the script that way. Why is one way of getting the filename better than another?
-
Start python3.6 to start the python3.6 shell, and use open from the prompt just like in this
program. Notice how you can open files and run read on them from within python3.6? -
Have your script also call close() on the txt and txt_again variables. It’s important to
close files when you are done with them.
补充
-
始终记住是
open
read
close
的顺序。 -
txt
变量并不是存储文件内容,而是一个file
Object,具体后文再谈。 -
Python并不限制文件的打开次数。