exercise 15
2017-12-31 本文已影响0人
不娶名字
# 从sys模块中导入argu功能
from sys import argv
# 解包,分别把输入值放入script和filename
script, filename = argv
令把文件对象赋值给txt
txt = open(filename)
# 输出
print(f"Here's your file {filename}:")
输出txt引用对象的内容
print(txt.read())
# 重复上面内容
print("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
print(txt_again.read())
练习
- Above each line, write out in English what that line does.
- 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 the 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.
答案
print("输入文件名")
filename = input(">")
txt = open(filename)
print(f"Here is your {filename}")
print(txt.read())
再次运行 python 在命令行下使用 open 打开一个文件,这种 open 和 read 的方法也值得一学。
>python
>print open("15.txt").read()
1
2
两种方式输出都相同,即为文件中的内容
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.