1.文件读写
1)使用open()打开一个文件
>>> f = open('/Users/michael/test.txt', 'r')
2)使用read()方法一次性读取全部内容
>>> f.read()
'Hello, world!'
使用read(size)方法一次性读取size字节内容
调用readline()可以每次读取一行内容
调用readlines()一次读取所有内容并按行返回list
3)使用close()方法关闭文件
>>> f.close()
为了保证无论是否出错都能正确地关闭文件,我们可以使用try … finally来实现:
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
with写法更简洁
with open('/path/to/file', 'r') as f:
print(f.read())
4 ) 读取二进制文件
rb模式打开文件
>>> f = open('/Users/michael/test.jpg', 'rb')
>>> f.read()
b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...' # 十六进制表示的字节
5)读取指定字符编码的文件
>>> f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')
>>> f.read()
'测试'
遇到有些编码不规范的文件,你可能会遇到UnicodeDecodeError,因为在文本文件中可能夹杂了一些非法编码的字符。遇到这种情况,open()函数还接收一个errors参数,表示如果遇到编码错误后如何处理。最简单的方式是直接忽略:
>>> f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore')
6)写文件
>>> f = open('/Users/michael/test.txt', 'w')
>>> f.write('Hello, world!')
>>> f.close()
你可以反复调用write()来写入文件,但是务必要调用f.close()来关闭文件。当我们写文件时,操作系统往往不会立刻把数据写入磁盘,而是放到内存缓存起来,空闲的时候再慢慢写入。只有调用close()方法时,操作系统才保证把没有写入的数据全部写入磁盘。忘记调用close()的后果是数据可能只写了一部分到磁盘,剩下的丢失了。所以,还是用with语句来得保险:
with open('/Users/michael/test.txt', 'w') as f:
f.write('Hello, world!')
2.StringIO和BytesIO
1)StringIO就是在内存中读写str
要把str写入StringIO,我们需要先创建一个StringIO,然后,像文件一样写入即可
>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue())
hello world!
getvalue()方法用于获得写入后的str。
要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取:
>>> from io import StringIO
>>> f = StringIO('Hello!\nHi!\nGoodbye!')
>>> while True:
... s = f.readline()
... if s == '':
... break
... print(s.strip())
...
Hello!
Hi!
Goodbye!
2)BytesIO实现了在内存中读写bytes
写入
>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
读取
>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87'
3.操作文件和目录
使用Python内置的os模块直接调用操作系统提供的接口函数
基本函数
1.操作系统类型 os.name
如果是posix,说明系统是Linux、Unix或Mac OS X,如果是nt,就是Windows系统。
>>> import os
>>> os.name # 操作系统类型
'posix'
2.获取详细的系统信息 os.uname()
注意uname()函数在Windows上不提供,也就是说,os模块的某些函数是跟操作系统相关的。
>>> os.uname()
posix.uname_result(sysname='Darwin', nodename='MichaelMacPro.local', release='14.3.0', version='Darwin Kernel Version 14.3.0: Mon Mar 23 11:59:05 PDT 2015; root:xnu-2782.20.48~5/RELEASE_X86_64', machine='x86_64')
3.环境变量 os.environ
>>> os.environ
environ({'VERSIONER_PYTHON_PREFER_32_BIT': 'no', 'TERM_PROGRAM_VERSION': '326', 'LOGNAME': 'michael', 'USER': 'michael', 'PATH': '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/mysql/bin', ...})
要获取某个环境变量的值,可以调用os.environ.get(‘key’)
操作文件和目录
1.查看、创建和删除目录
# 查看当前目录的绝对路径:
>>> os.path.abspath('.')
'/Users/michael'
# 在某个目录下创建一个新目录,首先把新目录的完整路径表示出来:
>>> os.path.join('/Users/michael', 'testdir')
'/Users/michael/testdir'
# 然后创建一个目录:
>>> os.mkdir('/Users/michael/testdir')
# 删掉一个目录:
>>> os.rmdir('/Users/michael/testdir')
# 把一个路径拆分为两部分
>>> os.path.split('/Users/michael/testdir/file.txt')
('/Users/michael/testdir', 'file.txt')
# 直接得到文件扩展名
>>> os.path.splitext('/path/to/file.txt')
('/path/to/file', '.txt')
# 对文件重命名:
>>> os.rename('test.txt', 'test.py')
# 删掉文件:
>>> os.remove('test.py')
2.利用Python的特性来过滤文件
列出当前目录下的所有目录
[x for x in os.listdir(".") if os.path.isdir(x)]
列出当前目录下的所有.py文件
[x for x in os.listdir(".") if os.path.isfile(x) and os.path.splitext(x)[1]==".py"]
4.序列化
我们把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。
序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。
反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。
Python提供了pickle模块来实现序列化
- dumps()和loads()
dumps()方法把任意对象序列化成一个bytes,然后把这个bytes写入文件
从文件中读取bytes再用loads()反序列化成一个对象
import pickle
###write
d1=dict(name='Bob', age=20, score=88)
b1=pickle.dumps(d1)
with open("file1.txt","wb") as f:
f.write(b1)
f.close()
###read
with open("file1.txt","rb") as f:
b2=f.read()
d2=pickle.loads(b2)
f.close()
print(d1==d2)
2.dump()和load()
pickle.dump()直接把对象序列化后写入一个file-like Object
pickle.load()方法从一个file-like Object中直接反序列化出对象
import pickle
#write
d3=dict(name='Bob', age=20, score=88)
with open("file2.txt","wb") as f:
pickle.dump(f,d3)
##read
with open("file2.txt","rb") as f:
d4=pickle.load(f)
print(d3==d4)
json
Python语言特定的序列化模块是pickle,但如果要把序列化搞得更通用、更符合Web标准,就可以使用json模块。
object—>json:
dumps()方法返回一个str,内容就是标准的JSON。类似的,dump()方法可以直接把JSON写入一个file-like Object。
>>> import json
>>> d = dict(name='Bob', age=20, score=88)
>>> json.dumps(d)
'{"age": 20, "score": 88, "name": "Bob"}'
json—>object:
loads()JSON的字符串反序列化,loads()从file-like Object中读取字符串并反序列化:
>>> json_str = '{"age": 20, "score": 88, "name": "Bob"}'
>>> json.loads(json_str)
{'age': 20, 'score': 88, 'name': 'Bob'}
class—->json:
import json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def student2dict(std):
return {
'name': std.name,
'age': std.age,
'score': std.score
}
s = Student('Bob', 20, 88)
print(json.dumps(s, default=student2dict))
print(json.dumps(s, default=lambda obj: obj.__dict__))
__dict__把任意class的实例变为dict
json—–>class:
def dict2student(d):
return Student(d['name'], d['age'], d['score'])
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str, object_hook=dict2student))