Python学习笔记(四) IO编程

1.读文件

使用open()函数打开文件,返回一个文件对象,可选择传参模式和缓冲区,默认是读模式,缓冲区是无
利用open()函数可以打开文件, 如下代码,open()的第二个参数是’r’,表示的是读文件,第三个参数encoding指定的是文件的编码格式.

filePath = 'D:/cc.txt'
f = open(filePath, 'r', encoding='UTF-8')
fileContent = f.read()
#文档使用完必须关闭,释放资源
f.close()
print(fileContent)

由于在读写文件的时候,也会发生异常,导致f.close()调不到,可以使用with语句来自动帮我们调用close()方法

with open(filePath, 'r', encoding='UTF-8') as readFile:
    print(readFile.read())

1.1读取每一行

调用read()是读取文件全部内容到内存,如果文件太大容易内存不足.
调用readline()每次读取一行内容

with open('D:/caesar-local.log', 'r', encoding='UTF-8') as logFile:
    thisLine = logFile.readline()
    while thisLine:
        print(thisLine)
        thisLine = logFile.readline()#再读取一行

或者

with open('D:/caesar-local.log', 'r', encoding='UTF-8') as logFile:
   for line in logFile.readlines():
       print(line.strip())

2.写文件

写文件和读文件一样,也是调用open()函数,区别是传入的是’w’
以’w’模式写入文件时,如果文件已存在,会直接覆盖(相当于删掉后新写入一个文件)。如果我们希望追加到文件末尾怎么办?可以传入’a’以追加(append)模式写入

filePath = 'D:/cc.txt'
with open(filePath, 'w') as f:
    f.write("Hello, pigg!")

3.序列化

3.1pickle模块来实现序列化

try:
    import cPickle as pickle
except ImportError:
    import pickle

#定义一个字典
d = dict(name='winter', age=13)
#dumps方法可将对象转成str
str_d = pickle.dumps(d)
print('str_d = ', str_d)

#dump方法可以将序列化的对象直接写入文件中
f = open('d:/a.txt', 'wb')
pickle.dump(d, f)
f.close()

保存到文件里的值是看不懂的字节

€}q (X   nameqX   winterqX   ageqKu.

当我们要把对象从磁盘读到内存时,可以先把内容读到一个bytes,然后用pickle.loads()方法反序列化出对象,也可以直接用pickle.load()方法从一个file-like Object中直接反序列化出对象

d = pickle.loads(str_d)
print("d = ", d)

file = open('d:/a.txt', 'rb')
d = pickle.load(file)
file.close()
print(d)
d =  {'name': 'winter', 'age': 13}
{'name': 'winter', 'age': 13}

3.2JSON

Python内置的json模块提供了非常完善的Python对象到JSON格式的转换。我们先看看如何把Python对象变成一个JSON

import json
user = dict(name='wd', age=28)
userJson = json.dumps(user)
print(userJson) #打印出{"name": "wd", "age": 28}

猜你喜欢

转载自blog.csdn.net/winterking3/article/details/81669697