open(path, mode, encoding='xxx', errors='ignore')json
mode取值:
rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
w 以写方式打开,
a 以追加模式打开 (从 EOF 开始, 必要时建立新文件)
r+ 以读写模式打开,先读后写(注意须要将文件指针重置为0,f.seek(0), 不然将变成追加内容)
w+ 以读写模式打开 (参见 w ), 先写后读
a+ 以读写模式打开 (参见 a )
rb 以二进制读模式打开
wb 以二进制写模式打开 (参见 w )
ab 以二进制追加模式打开 (参见 a )
rb+ 以二进制读写模式打开 (参见 r+ )
wb+ 以二进制读写模式打开 (参见 w+ )
ab+ 以二进制读写模式打开 (参见 a+ )编码
示例代码:spa
f = open('a.txt', 'r') content = f.read() f.close() print(content)
示例代码2:指针
f = open('a.txt', 'r') content = '' for line in f.readlines(): content += line.strip() #过滤尾部换行符 f.close() print(content)
示例代码3:code
f = open('a.txt', 'r') content = '' for line in f.readlines(): content += line.strip() #过滤尾部换行符 f.close() print(content)
content = '' try: f = open('a.txt', 'r') for line in f.readlines(): content += line.strip() #过滤尾部换行符 except BaseException: pass finally: f.close() print(content)
示例代码对象
content = '' with open('a.txt', 'r') as f: for line in f.readlines(): content += line.strip() #过滤尾部换行符 print(content)
示例代码:blog
with open('a.txt', 'a') as f: f.writelines(['Hello, world!\n','Hello, world!\n'])
借助StrongIO和文件读写大体相同,调用close时,内存释放ip
示例:内存
from io import StringIO f = StringIO() f.write('hello') f.write('word') print(f.getvalue()) f.close()
借助BytesIO和文件读写大体相同,调用close时,内存释放utf-8
from io import BytesIO f = BytesIO() f.write('你'.encode('utf-8')) #写入通过UTF-8编码的bytes f.write('好'.encode('utf-8')) #写入通过UTF-8编码的bytes print(f.getvalue()) f.close()
>>> import os >>> os.name 'nt'
posix,说明系统是Linux、Unix或Mac OS X,若是是nt,就是Windows系统。
>>> os.environ >>> os.environ.get('PATH') #获取其中一项
os.path模块中的方法
>>> os.path.abspath('.') #当前目录绝对路径 >>> os.path.join(os.path.abspath('.'), 'test') #合并路径 >>> os.mkdir('ror') #建立目录 >>> os.rmdir('ror') #删除目录 >>> os.rename('test.txt', 'test.py') #文件重命名 >>> os.remove('test.py') #删除文件
#拆分路径 >>> os.path.split('/usr/ror/a.txt') ('/usr/ror', 'a.txt') #拆分扩展名 >>> os.path.splitext('/usr/ror/a.txt') ('/usr/ror/a', '.txt')
#列出当前目录下全部的txt文件 >>> [file for file in os.listdir('.') if os.path.isfile(file) and os.path.splitext(file)[1] == '.txt'] #拷贝文件(拷贝当前目录下a.txt到b.txt) >>> import shutil >>> shutil.copyfile('a.txt', 'b.txt')
示例代码:
>>> import pickle >>> d=dict(age=10,name='g') >>> pickle.dumps(d) #dumps 方法把任意对象序列化成一个bytes >>> f=open('a.txt', 'wb') >>> pickle.dump(d, f) #dump()直接把对象序列化后写入一个文件对象 >>> f.close()
能够先把内容读到一个bytes,而后用pickle.loads()方法反序列化出对象,也能够直接用pickle.load()方法从一个文件对象中直接反序列化出对象
>>> f=open('a.txt', 'rb') >>> d=pickle.load(f) >>> f.close() >>> d {'age': 10, 'name': 'g'}
>>> import json >>> d=dict(age=10,name='g') >>> json_str = json.dumps(d) #从字典/对象序列化 >>> json_str '{"age": 10, "name": "guobin"}' >>> json.loads(json_str) #从字符串反序列化 {u'age': 10, u'name': u'guobin'}
示例代码
import json class Foo: def __init__(self, name, age): self.name = name self.age = age # json encode obj f = Foo('g', 15) print(json.dumps(f.__dict__)) #json decode obj def hook(d): return Foo(d['name'], d['age']) f2 = json.loads('{"name": "g", "age": 15}', object_hook= hook) print(f2)
输出:{"name": "g", "age": 15}<__main__.Foo object at 0x00000213E383A940>