EX16: Reading and Writing Files
-
例子:
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...") # w 新建只写,w+ 新建读写,二者都会将文件内容清零(以 w 方式打开,不能读出。w+ 可读写) 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()
没有
target.close()
,文件内容也会保存。但是这个命令非常有必要,特别是用.write()
做循环时。当程序越来越复杂时,如果没有close()
命令,会导致文件一直运作,直到电脑崩溃。 -
学习内容:
readline()
;write()
;seek()
;truncate()
;open()
中的w
、wb
、w+
、r
、rb
、r+
、a
、a+
;-
readline()
-
readline()
方法每次读取一行;返回的是一个字符串对象,保持当前行的内存 -
readline()
读取整行,包括行结束符,并作为字符串返回 -
read()
,readline()
,readlines()
的区别read()
:读取整个文档,直接读取字节到字符串中,包括了换行符readline()
:每次只读取一行,读取后再次执行该命令,会读取下一行readlines()
:一次性读取整个文件;自动将文件内容分析成一个行的列表。输入:
from sys import argv script, filename = argv txt = open(filename, 'r') a = txt.read() txt.seek(0) b = txt.readline() txt.seek(0) c = txt.readlines() print("用read()读取文档: " , a)
-
-