from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
# 打印
print(f"We're going to erase {filename}.")
# 打印
print("If you don't want that, hit CTRL-C (^C).")
# 打印
print("If you do want that, hit RETURN.")
# 这个input()仅仅是等待输入,按任意键输入就会运行程序,按ctrl-c就会终止运行
input("?")
# 打印
print("Opening the file...")
# 在文件中写入
target = open(filename, 'w')
# 打印
print("Truncating the file. Goodbye!")
# 清除文件内容
target.truncate()
# 打印
print("Now I'm going to ask you for three lines")
# 输入第一行
line1 = input("line 1: ")
# 输入第二行
line2 = input("line 2: ")
# 输入第三行
line3 = input("line 3: ")
# 打印
print("I'm going to write these to the file.")
# 文件中写入第三行
target.write(line1)
#文件中换行
target.write("\n")
# 文件中写入第三行
target.write(line2)
# 文件中换行
target.write("\n")
# 文件写入第三行
target.write(line3)
# 写入,换行
target.write("\n")
# 打印
print("And finally, we close it.")
# 关闭文件
target.close()
练习
- If you do not understand this, go back through and use the comment trick to get it squared away inyour mind. One simple English comment above each line will help you understand or at least let youknow what you need to research more.
- Write a script similar to the last exercise that uses read and argv to read the file you just created.
- There’s too much repetition in this file. Use strings, formats, and escapes to print out line1 ,line2 , and line3 with just one target.write() command instead of six.
- Find out why we had to pass a 'w' as an extra parameter to open . Hint: open tries to be safe by making you explicitly say you want to write a file.
- If you open the file with 'w' mode, then do you really need the target.truncate() ? Read thedocumentation for Python’s open function and see if that’s true.
答案
from sys import argv
script,filename = argv
txt = open(filename,'r')
print(txt.read())
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
# 打印
print(f"We're going to erase {filename}.")
# 打印
print("If you don't want that, hit CTRL-C (^C).")
# 打印
print("If you do want that, hit RETURN.")
# 这个input()仅仅是等待输入,按任意键输入就会运行程序,按ctrl-c就会终止运行
input("?")
# 打印
print("Opening the file...")
# 在文件中写入
target = open(filename, 'w')
# 打印
print("Truncating the file. Goodbye!")
# 清除文件内容
target.truncate()
# 打印
print("Now I'm going to ask you for three lines")
# 输入第一行
line1 = input("line 1: ")
# 输入第二行
line2 = input("line 2: ")
# 输入第三行
line3 = input("line 3: ")
# 打印
print("I'm going to write these to the file.")
# 文件中写入第三行
target.write(f"{line1}\n{line2}\n{line3}\n")
# 打印
print("And finally, we close it.")
# 关闭文件
target.close()
5.没必要用target.truncate(),用为read模式会覆盖原文件。
Q: 'w'参数是什么意思?
它只是打开文件的一种模式。如果你用了这个参数,表示"以写(write)模式打开文件。同样有'r'表示只读模式,'a'表示追加模式,还有一些其他的修饰符。
Q: 有什么修饰符我可以用在打开文件的模式上?
最重要的一个就是+, 使用它,你可以有'w+', 'r+', 和'a+'模式. 这样可以同时以读写模式打开文件。
Q: open(filename)是以'r' (只读) 模式打开文件吗?
是的,'r' 是 open()函数的默认参数值。