1、文件读写:
file = open('file_name.txt','w',encoding='utf-8') names = ['a','b','c'] n='wang,123' file.write(n) #多用于字符串 #file.writelines(n) for name in names: file.write(name) #for name in names: # file.writelines(names)
import time file = open('hahaha','w') file.write('kakaka') file.flush() #立即把缓冲区里面的内容写到磁盘里面 with open('file_name.txt','w') as a , open('file_name2.txt') as a2: #打开多个文件 a.write('123') a2.write('456')
2、以二进制模式打开图片:
import requests url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1515746419895&di=9aa9a8429799de178ba0cc9cf06c89e9&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01a2e6567ce0bd6ac725ad903aa9bb.jpg' img = requests.get(url).content f = open('xiaohei.jpg','wb') #bytes,以二进制模式打开 f.write(img)
3、修改文件两种方式:
1/
with open('nums', 'a+', encoding='utf-8') as f: f.seek(0) all = f.read() new_num = all.replace('1', '2') #a为旧字符串,b为新字符串 f.seek(0) f.truncate() f.write(new_num) f.flush()
2/ import os with open('nums',encoding='utf-8') as f, open('nums.gy','w',encoding='utf-8') as f2: for line in f: new_line = line.replace('1', '2') f2.write(new_line) os.remove('nums') #删文件 os.rename('nums.gy', 'nums') #改名