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('line1: ')
line2=input("line2: ")
line3=input("line3: ")
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")
newlineall=line1+"\n"+line2 + "\n" + line3 + "\n"
target.write(newlineall)
print("and finally, we close it.")
target.close()
结果为:
*close
关闭文件
*read
读取文件内容
*readline
只读取文本文件中的一行
*truncate
清空文件,请小心使用该文件
*write('stuff')
将stuff写入文件
*seek(0)
将读写位置移动到文件开头
*open
多传入一个‘w
’,open对文件的写入操作态度是安全第一,特别指定才能写入
*open
默认为读取
*r
读取,w
写入,a
追加
*
修饰符 + 'w+' 'a+' 'r+'
可以把文件同时用读写的方法打开