1-文件读写
f = open('d:/file.txt','r') #如果文件不存在会报异常print(f.read()) #一次性读取所有内容f.close()
1.2 由于文件操作会用异常, 每次用try不方便
with open("d:/file.txt","r") as f: print(f.read())
1.3 文件太大,一次性读取不科学,如果是配制文件
with open("d:/file.txt","r") as f: for line in f.readlines(): print(line.strip())
1.4 指定字符编码
f = open('d:/file.txt', 'r', encoding='gbk',errors='ignore') #errors='ignore' 参数会忽略中的一些编码错误f.read()
1.5 写文件,w会删除原来的,a是追加
f = open('d:/file.txt', 'a')f.write("go out")f.close()
2-StringIO和BytesIO
StringIO顾名思义就是在内存中读写str。from io import StringIOf = StringIO()f.write('hello')f.write(' ')f.write('word!')print(f.getvalue()) #hello word!
2.2 BytesIO
StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIOfrom io import BytesIOf = BytesIO()f.write('中文'.encode('utf-8'))print(f.getvalue()) #b'\xe4\xb8\xad\xe6\x96\x87'#初始化BytesIOfrom io import BytesIOf = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')print(f.read())
3-操作文件和目录
3.1环境变量
import osos.environ#环境变量os.environ.get('OS') #得到指定的key
3.2 文件路径操作
os.path.abspath(".")os.path.join('d:/','fffff')os.mkdir("d:/testdir") #如果存在创建会报错os.rmdir("d:/testdir")
3.3 文件路径
os.path.split('/Users/michael/testdir/file.txt')#('/Users/michael/testdir', 'file.txt') os.rename('test.txt', 'test.py') #对文件重命名 os.remove('test.py') #删除文件[x for x in os.listdir('.') if os.path.isdir(x)] #列出当前目录下的所有目录[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py'] #列出所有的.py文件
4-序列化操作(在其他语言中也被称之为serialization,marshalling,flattening等等)
import pickled = dict(name='Bob', age=20, score=88)print(pickle.dumps(d))f=open('dump.txt','wb') pickle.dump(d,f) #序列化到文件f.close()
4.2 反序列化
f = open('dump.txt','rb')d=pickle.load(f)#反序列化f.close()print(d)
4.3 json序列化
import jsond = dict(name='Bob111', age=20, score=88)print(json.dumps(d))
4.4 json序列化 进阶
import jsonclass Student(object): def __init__(self,name,age,score): self.name = name self.age = age self.score = scores = Student('dashen', 20, 80)def student2dict(std): return { 'name':std.name, 'age':std.age, 'score':std.score } print(json.dumps(s,default=student2dict))print(json.dumps(s,default=lambda obj:obj.__dict__))
4.5 json反序列化
def dict2student(d): return Student(d['name'], d['age'], d['score'])json_str = '{"age": 20, "score": 88, "name": "Bob"}'stu = json.loads(json_str, object_hook=dict2student)print(stu.score) #88