一、文件读写
python用open()函数打开文件:
open(name,mode,encoding,errors)
name为文件名,可以加路径。
encoding表示的是返回的数据采用何种编码,一般采用utf8或者gbk;
正确路径的三种方法:
>>> f=open(r"D:\vx\auth_info_key_prefs.xml")
>>> f=open("D:\\vx\\auth_info_key_prefs.xml")
>>> f=open("D:/vx/auth_info_key_prefs.xml")
mode 文件模式(常用):
‘r’ 读取模式(默认值);
’w’ 写入模式;
‘a’ 附加模式;
‘b’ 二进制模式(可结合其他模式);
’t’ 文本模式(默认值);
‘+’ 读写模式(可结合其他模式);
‘w+’ ‘r+’ 区别就是前面的模式打开文件会直接删除文件内容。‘r+’不会删除文件内容,但是会覆盖。
读写文件类似于管道
参考文件覆盖
>>> f=open("D:/123.txt",'r+')
>>> print(f.read()) #读文件
123456789123456789
>>> print(f.read()) #类似于管道 输出就没了
>>> f.close() #关了才会写入文件
>>> f=open("D:/123.txt",'r+')
>>> f.write("yxd") #写文件
3
>>> print(f.read())
456789123456789
>>> f.close()
>>> f=open("D:/123.txt",'r+')
>>> print(f.read())
yxd456789123456789
>>> f=open("D:/123.txt",'r+') #可以在内容后面写
>>> print(f.read())
yxd456789123456789
>>> f.write("yxd")
3
>>> f.close()
>>> f=open("D:/123.txt",'r+')
>>> print(f.read())
yxd456789123456789yxd
>>> f=open("D:/123.txt",'w+') #原本有内容
>>> print(f.read())
>>> f.close()
随机存取
seek(offset[,whence])
offset:字符数,偏移量;
tell()
返回当前位于文件的位置;
>>> f=open(r'D:\1.txt','w')
>>> f.write("123456789123456789")
18
>>> f.seek(6)
6
>>> f.write('Hello')
5
>>> f.close()
>>> f=open(r'D:\1.txt')
>>> f.read() #可以带参数表示读取字符个数
'123456Hello3456789'
可自动关闭文件的语句
with open(r’D:\1.txt’,‘w’) as f:
do_something(f)
打开文件并赋值给变量(f),并在语句结尾,自动关闭文件;
文件方法:
read() :读文件;
write() : 写文件;
readline() : 每次读取一行;
readlines() : 读取所有行,以列表形式返回;
>>> open(r'D:\1.txt').readlines()
['123456Hello3456789\n', '123\n', 'hello;']
writelines() :把一个字符串列表写入文件(需要自己加换行符‘\n’);
也有一种不加换行符写文件用print:
>>> with open(r"D:\1.txt",'w') as f:
print('fist','lala',file=f)
print('finally','haha',file=f)
>>> lines=list(open(r'D:\1.txt')) #与readlines()类似
>>> lines
['fist lala\n', 'finally haha\n']
也可以直接用for循环迭代文件,也可以利用以上方法:
>>> with open(r'D:\1.txt') as f:
for line in f:
print(line)
123456Hello3456789
123
hello;