读写文件 (写入w、读取r、追加a)Python3
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.")
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()
文件相关命令
- close:关闭文件。
- read:读取文件,把结果赋给一个变量
- readline:只读取文本文件的一行
- truncate:清空文件
- write(‘stuff’):将stuff写入文件
- seek(0):将读写位置移动到文件开头
readline() 方法语法如下:
fileObject.readline()
readline() 方法用于从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符。
open的参数
target = open(filename, 'w') #以写入模式打开文件
- ‘w’--write写入模式
- ‘r’--read读取
- ‘a’--append追加
- 可以使用加号修饰符+:‘w+’,‘r+’,‘a+’;可以把文件同时以读写方式打开
- open默认为‘r’