Learn to Code

《笨办法学Python3》练习十六:读写文件

2019-03-02  本文已影响0人  雨开Ame

练习代码

from sys import argv

script, filename = argv

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("? ")

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()

Study Drills

  1. If you do not understand this, go back through and use the comment trick to get it squared away in your mind. One simple English comment above each line will help you understand or at least let you know what you need to research more.

  2. Write a script similar to the last exercise that uses read and argv to read the file you just
    created.

  3. 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.

target.write(line1+"\n"+line2+"\n"+line3+"\n")
  1. 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.

open()方法的默认模式是r,也就是只读模式,无法写入。

  1. If you open the file with 'w' mode, then do you really need the target.truncate()? Read
    the documentation for Python’s open function and see if that’s true.

不是必需的。w模式会在写入前自动truncate
详见 官方文档

补充

  1. open的常用模式
    chrome_rMhjam4m4c.png
上一篇 下一篇

猜你喜欢

热点阅读