在习题ex15中进行了文件的读操作,下面这道习题中增加了写操作,文件的读和写是文件操作中最为常见的两种操作。不过在开始读写文件的操作前,需要对下面这些Python(其它语言也类似)中对于文件操作的函数先好好理解一下。
函数名称 | 函数功能 |
---|---|
close | 关闭文件 |
read | 读取文件内容 |
readline | 读取文本文件中的一行 |
truncate | 清空文件 |
write | 写入文件 |
seek | 读写位置移动到指定位置 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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()
运行上面这段程序,结果如下:
ex16运行结果
上面这段程序基本上较为全面的使用了文件操作中最为基本的一些操作。结合运行结果,我们梳理下ex16代码段的含义。
- 首先执行命令时确定了文件为test.txt;
- 接着以可写方式打开了该文件;
- 然后清空了该文件的内容;
- 用户输入了3行内容,并且分别保存起来;
- 最后将用户输入的内容存入文件,并且关闭。
运行完ex16中的程序,打开test.txt文件,可以看到确实把用户输入的3行内容写入了文件。不信,你动手试试?
小结
- 熟悉和理解Python中对于文件的常用操作。