python日记----2017.7.24

字符编码

1 以什么编码存的就要以什么编码取出
ps:内存固定使用unicode编码,
我们可以控制的编码是往硬盘存放或者基于网络传输选择编码

2 数据是最先产生于内存中,是unicode格式,要想传输需要转成bytes格式
#unicode----->encode(utf-8)------>bytes
拿到bytes,就可以往文件内存放或者基于网络传输
#bytes------>decode(gbk)------->unicode

3 python3中字符串被识别成unicode
python3中的字符串encode得到bytes

4 了解
python2中的字符串就bytes
python2中在字符串前加u,就是unicode

文件处理

1.只读模式'r':只能对文件执行读操作,文件不存在会报错。

read():读取文件

open():打开文件

close():关闭文件{一定要关闭}

readline():一行一行的执行

readlines():读取所有的行,存成一个列表的的形式

readable:()检测该文件是否可读,返回True或False

2.只写模式;‘w’,文件不存在则创建,存在就清空

writeable():检测文件是否可写,返回True或False

write(str)的参数是一个字符串,就是你要写入文件的内容.

writelines(sequence)的参数是序列,比如列表,它会迭代帮你写入文件。

3.之追加模式‘a’:文件不存在则添加,如果文件存在文件内容最后进行追加。

rb:读取
f=open('aaaa.py','rb')
print(f.read().decode('utf-8'))

f=open('1.jpg','rb')
data=f.read()

wb:写入
f=open('2.jpg','wb')
f.write(data)
f=open('new_3.txt','wb')
f.write('aaaaa '.encode('utf-8'))

wb:追加写入
f=open('new_3.txt','ab')
f.write('aaaaa '.encode('utf-8'))

上下文管理:

with open('aaaa.py','r',encoding='utf-8') as read_f,
open('aaaa_new.py','w',encoding='utf-8') as write_f:
data=read_f.read()
write_f.write(data)


循环取文件每一行内容
with open('a.txt','r',encoding='utf-8') as f:
while True:
line=f.readline()
if not line:break
print(line,end='')

lines=f.readlines() #只适用于小文件
print(lines)

data=f.read()
print(type(data))


for line in f: #推荐使用
print(line,end='')
文件的修改
方式一:只适用于小文件
import os
with open('a.txt','r',encoding='utf-8') as read_f,
open('a.txt.swap','w',encoding='utf-8') as write_f:
data=read_f.read()
write_f.write(data.replace('alex_SB','alex_BSB'))

os.remove('a.txt')
os.rename('a.txt.swap','a.txt')


方式二:
import os
with open('a.txt','r',encoding='utf-8') as read_f,
open('a.txt.swap','w',encoding='utf-8') as write_f:
for line in read_f:
write_f.write(line.replace('alex_BSB','BB_alex_SB'))

os.remove('a.txt')
os.rename('a.txt.swap','a.txt')


原文地址:https://www.cnblogs.com/De-Luffy/p/7230852.html