python_cookbook记录

文件和io(cookbook笔记)

2017-07-27  本文已影响0人  buildbody_coder

读写文本数据

读写文本数据

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
with open('somefile.txt', 'rt', newline='') as f:
    pass
with open('somefile.txt', 'rt', encoding='latin-1') as f:
    pass

打印输出至文件中

def print_out():
    with open('test.txt', 'wt') as f:
        print("Hello World", file=f)

使用其他分隔符或行终止符打印

>>> print ('aaa', 90, 51, sep=',', end='!!!')
aaa,90,51!!!
#在输出中禁止换行
>>> for i in range(5):
...     print (i, end=' ')
0 1 2 3 4 

读写字节数据

>>> t = "hello world"
>>> t[0]
'h'
>>> t = b"hello world"
>>> t[0]
104
def wr_encode():
    with open('test.bin', 'wb') as f:
        f.write('hello world'.encode('utf-8'))
def rd_decode():
    with open('test.bin', 'rb') as f:
        data = f.read(16)
        text = data.decode('utf-8')

防止写的文件被覆盖

>>> with open('test.txt', 'wt') as f:
...     f.write('Hello world')
>>> with open('test.txt', 'xt') as f:
...     f.write('Hello world')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
      with open('test.txt', 'xt') as f:
      FileExistsError: [Errno 17] File exists: 'test.txt'
#也可以在写前面检测文件是否存在
>>> import os
>>> os.path.exists('test.txt')
True

固定大小的文件迭代

from functools import partial
RECORD_SIZE = 32
def size_rb():
    with open('somefile.data', 'rb') as f:
        records = iter(partial(f.read, RECORD_SIZE), b'')
        for r in records:
            print (r)

读取二进制数据到可变缓冲区中

import os
def read_into_buffer(filename):
    #设定缓冲区大小
    buf = bytearray(os.path.getsize(filename))
    with open(filename, 'rb') as f:
        f.readinto(buf)
    return buf

if __name__ == '__main__':
    with open('sample.bin', 'wb') as f:
        f.write(b'Hello World')
    #读取数据到缓冲区
    buf = read_into_buffer('sample.bin')
    with open('newsample.bin', 'wb') as f:
        f.write(buf)

内存映射的二进制文件

import os
import mmap

def memory_map(filename, access=mmap.ACCESS_WRITE):
    size = os.path.getsize(filename)
    fd = os.open(filename, os.O_RDWR)
    return mmap.mmap(fd, size, access=access)

if __name__ == '__main__':
    size = 1000000
    with open('data', 'wb') as f:
        #设置文件的起始位置
        f.seek(size-1)
        f.write(b'\x00')

    with memory_map('data') as m:
        print (len(m))
        m[0:11] = b'hello world'
        print (m[0:11])

文件路径名的操作

>>> import os
>>> path = '/Users/beazley/Data/data.csv'
>>> os.path.basename(path)
'data.csv'
>>> os.path.dirname(path)
'/Users/beazley/Data'
>>> os.path.join('tmp', 'data', os.path.basename(path))
'tmp/data/data.csv'
>>> path = '~/Data/data.csv'
>>> os.path.expanduser(path)
'/Users/gongyulei/Data/data.csv'
>>> os.path.splitext(path)
('~/Data/data', '.csv')

测试文件是否存在

>>> os.path.exists('/etc/passwd')
True
>>> os.path.exists('/tmp/spam')
False
>>> os.path.exists('/tmp/')
True
>>> os.path.isfile('/etc/passwd')
True
>>> os.path.isdir('/etc/passwd')
False
#软连接测试
>>> os.path.islink('/usr/local/bin/python3')
True
#文件的真实路径
>>> os.path.realpath('/usr/local/bin/python3')
'/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/bin/python3.6'
#获取大小
>>> os.path.getsize('/etc/passwd')
5925

获取文件夹中的文件列表

#结果会返回目录中所有文件列表
>>> os.listdir('.')
['ch5_10.py', 'ch5_2.py', 'ch5_4.py', 'ch5_8.py', 'ch5_9.py', 'data', 'newsample.bin', '
sample.bin', 'somefile.data', 'test.bin', 'test.gz', 'test.txt']
#执行某种过滤
>>> name = [name for name in os.listdir() if os.path.isfile(os.path.join('.', name))]
>>> name
['ch5_10.py', 'ch5_2.py', 'ch5_4.py', 'ch5_8.py', 'ch5_9.py', 'data', 'newsample.bin', '
sample.bin', 'somefile.data', 'test.bin', 'test.gz', 'test.txt']
>>> name = [name for name in os.listdir() if os.path.isdir(os.path.join('.', name))]
>>> name
['test']
>>> pyfils = [name for name in os.listdir() if name.endswith('.py')]
>>> pyfils
['ch5_10.py', 'ch5_2.py', 'ch5_4.py', 'ch5_8.py', 'ch5_9.py']
import os
import glob

def main():
    pyfiles = glob.glob('*.py')
    print (pyfiles)
    name_sz_date = [(name, os.path.getsize(name), os.path.getmtime(name))\
                   for name in pyfiles]
    for name, size, mtime in name_sz_date:
        print (name, size, mtime)

if __name__ == '__main__':
    main()

增加或改变已打开文件的编码

import urllib.request
import io

def encode_text():
    u = urllib.request.urlopen('http://www.python.org')
    f = io.TextIOWrapper(u, encoding='utf-8')
    #编码成utf-8
    text = f.read()
    print (text)

if __name__ == '__main__':
    encode_text()

创建临时文件和文件夹

from tempfile import NamedTemporaryFile, TemporaryDirectory

def create_tmp():
    #'w+t'为文本模式
    with NamedTemporaryFile('w+t', delete=False) as f:
        print ('filename is :', f.name)
        f.write('Hello World\n')
        f.write('Testing\n')
        f.seek(0)
        data = f.read()

    with TemporaryDirectory() as dirname:
        print ('dirname is :', dirname)

if __name__ == '__main__':
    create_tmp()

>>> from tempfile import NamedTemporaryFile
>>> f = NamedTemporaryFile(prefix='mytemp', suffix='.txt', dir='/tmp')
>>> f.name
'/tmp/mytempurb_uyz4.txt'
>>> 

序列化python对象

>>> import pickle
>>> f = open('test.txt', 'wb')
>>> pickle.dump([1, 2, 3], f)
>>> pickle.dump({'aaa', '111'}, f)
>>> f = open('test.txt', 'rb')
>>> pickle.load(f)
[1, 2, 3]
>>> pickle.load(f)
{'111', 'aaa'}
上一篇下一篇

猜你喜欢

热点阅读