python——文件操作

文件操作:

Windows中打开文件用r或者\

r原生字符串    转义符

f=open(r'C:Usersa.txt','rb')或者f=open('C:\Users\a.txt','rb')

读模式:

f=open('a.txt',encoding='utf-8')  # 这里要指定以什么编码方式打开文件。
 

# 读全文,只能读一次。
print(f.read())

#一次只读一行,默认在行尾添加换行符,用end来指定行尾的符号。
print(f.readline(),end='')

#读全文,存成列表的形式。
print(f.readlines())

f.close()

写模式

不存在则创建,存在则覆盖

f=open('a.txt','w',encoding='utf-8')           #以写的方式打开
f.write('2222222
') #末尾默认不带换行符
f.writelines(['11111
','22222
','3333
'])   #一次写多行
f.close()

追加模式

不存在则创建,追加的方式写

f=open('a.txt','a',encoding='utf-8')
f.write('
444444
')
f.close()

其它方法:

 

f=open('a.txt','w',encoding='utf-8')
f.write('asdfasdf')
f.flush() #把内存中的数据刷到硬盘
f.close()
print(f.closed) #判断文件是否关闭,false为未关闭
print(f.name,f.encoding)          #查看文件名称,查看编码方式
print(f.readable())               #查看文件句柄是否可读(文件句柄关闭前后都能执行)
print(f.writable())               #查看文件句柄是否可写(文件句柄关闭前执行)

文件内光标移动:

f=open('a.txt','r',encoding='utf-8')
1、移动光标

print(f.read(3))                  #读取三个字符,读完之后光标在第三个字符后面。
print('first_read: ',f.read())    #从第三个字符后面开始读。
f.seek(0)                         #将光标移动到指定位置
print('second_read: ',f.read())

2、查看光标的位置

f.seek(3)                        #seek以字节为单位,而utf-8中一个汉字占3个字节
print(f.tell())                  #查看当前光标在什么位置。

3、指定光标开始的位置

f.seek(3,0) 

#第二个参数有0,1,2

0代表从开头开始;

1表示从当前位置开始;

2表示从文件末尾开始,倒着取。格式f.seek(-3,2) 这种写法要求文件用rb或者wb的方式打开

f=open('a.txt', 'rb')

f.seek(3,0)
print(f.tell())

f.seek(3,1)
print(f.tell())

f.seek(3,2)
print(f.tell())

rb,wb,ab

rb,wb,ab 读的是bytes,写的是bytes,追加的也是bytes.

写的时候要编码,读的时候要解码。

 

1、以bytes的方式读

f=open('a.txt','rb')
print(f.read())                          #读出来的内容是bytes格式的
print(f.read().decode('utf-8'))          #bytes格式需要解码成Unicode
f.close()

2、  bytes的方式写

f=open('a.txt','wb')
print(f.write('你好啊'.encode('utf-8'))) #以wb的方式写,需要对数据进行编码
f.close()

输出结果:9  表示占9个字节

rb,wb,ab的方式操作文件的好处:不会有乱码。

3、图片或者视频就不能用字符的方式(encode,decode)编解码了

a=open('0.gif','rb')
b=open('0.copy.gif','wb')
b.write(a.read())

1truncate() 截断

f=open('c.txt','w',encoding='utf-8')
f.write('1111
')
f.write('2222
')   
f.truncate(3)  //只能在写模式使用truncate方法 #从开头开始,截断3个字节。其余的都删除。;;

修改文件的过程:

import os
read_f=open('a.txt','r',encoding='utf-8')
write_f=open('.a.txt.swp','w',encoding='utf-8')

for line in read_f:             #一行一行的读取,避免内存溢出
    if 'alex' in line:           #判断alex是否在这一行里
        #先改,再写入write_f 
        line=line.replace('alex','ALEXSB')       #替换
    write_f.write(line)               

read_f.close()
write_f.close()
os.remove('a.txt')
os.rename('.a.txt.swp','a.txt')

上下文管理(with)

with as的方式打开文件,当with的子代码执行完了之后,文件句柄会自动关闭。

with open('a.txt','r',encoding='utf-8') as read_f,
        open('.a.txt.swp','w',encoding='utf-8') as write_f:
    for line in read_f:
        if 'alex' in line:
            line=line.replace('alex','ALEXSB')
        write_f.write(line)
os.remove('a.txt')
os.rename('.a.txt.swp','a.txt')
原文地址:https://www.cnblogs.com/linuxws/p/10241362.html