python读写文件学习
在笨办法学python中,学到了argv
里面有段代码是
from sys import argv
#script,开始书上是另外一个函数,查阅资料,发现去掉这个
#原来是script,filename=argv但是运行不起,查资料是script是多的一个参数,不是函数,删掉就是了
filename= argv#sys是一个软件包
print(“We’re going to erase %r.”)#这里本来有%filename但是加了运行不了,现在还不知道为什么
print(" if you don’t want taht,hit CTRL_C")
print(“if you do want that ,hit enter”)
input("?")
print(“open the file…”)
target = open(‘text.txt’,‘w’)#w相当于对文件的写操作,就是write的意思
print(“Truncating the file. good bye!”)
target.truncate()#清空文件
print(“Now i’m going to ask you for three lines.”)
linel = input("line 1: ")
line2=input("line 2: ")
line3=input(“line 3:”)
print(“i’m going to write these to the file”)
target.write(linel)#写入第一行
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print(“And finally, we close it.”)
target.close()#关闭文件函数
所以说这就是对文件的基本操作
w相当于是写入模式
r表示读取模式
a表示追加模式,在不删除前面的情况下继续添加吧。
还可以r+w什么操作的
同时读写操作都可以
如果只写open(filename)那么就是默认r模式