习题16 读写文件(巩固练习)
练习1. 注释
from sys import argv # 导入模块(module)
script, filename = argv # 解包(unpacking)
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') # 参数'w'写入(write)模式,不可读;不存在则创建;存在则删除内容。
print("Truncating the file. Goodbye!")
target.truncate() # 前面必须有open()函数,truncate()待补充...
print("Now I'm going to ask 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() # 保存、关闭文件
练习2. 使用read和argv读取刚才新建的文件
from sys import argv
script, filename = argv
ex16_txt = open(filename, 'r')
print(ex16_txt.read())
ex16_txt.close()
运行结果:
$ python3.8 ex16_2.py ex16_test.txt
I'm not a big fan of household chores, so I feel quite bored when I have to buy groceries, wash the dishes or do the laundry.
I can't stand bananas, I think it's because the texture makes me gag.
I love drinking coffee. It gives me a boost in the morning.
练习3. 用一个target.write()将line1、line2和line3打印出来,替换掉原来的6行代码
target.write(f"{line1}\n{line2}\n{line3}\n")
练习4. 找出需要给open多传入一个’w’参数的原因
- ‘r’,只读(默认)。【不存在则返回:FileNotFoundError】
- ‘w’,只写。【不可读;不存在则创建;存在则删除内容;】
- ‘a’,追加(append)。【可读;不存在则创建;存在则只追加内容;】
"+" 修饰符,可以同时读写某个文件,“并根据使用的字符,以不一样的方式实现文件的定位”
- ‘r+’,可读写文件。【可读;可写;可追加】
- ‘w+’,写读。
- ‘a+’,同’a’。
练习5. 如果用’w’模式打开文件,是不是还需要target.truncate()呢?
truncate()前面必须有open()函数。
- 'r’模式,只读,无法截取;
- 'w’模式,自动覆盖原文件内容,目前来看无需使用truncate();
- 'a’模式,truncate()不起作用,不会清空原文件的内容。
补充:open()函数
open()函数完整语法格式:
open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
详见:菜鸟教程: link.
关于truncate()用法有待补充……