• 主页
  • 相册
  • 随笔
  • 目录
  • 存档
Total 244
Search AboutMe

  • 主页
  • 相册
  • 随笔
  • 目录
  • 存档

Python厨书笔记-6

2020-01-17

1. 文件IO

2. with

with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams

Supporting the “with” statement in user defined objects

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# a simple file writer object 

class MessageWriter(object):
def __init__(self, file_name):
self.file_name = file_name

def __enter__(self):
self.file = open(self.file_name, 'w')
return self.file

def __exit__(self):
self.file.close()

# using with statement with MessageWriter

with MessageWriter('my_file.txt') as xfile:
xfile.write('hello world')

首先,在例子程序中的with语句给被使用到的文件创建了一个上下文环境, 但 with 控制块结束时,文件会自动关闭。你也可以不使用 with 语句,但是这时候你就必须记得手动关闭文件

1
2
3
f = open('somefile.txt', 'rt')
data = f.read()
f.close()
  • rt 模式:读

  • wt 模式:覆盖写

  • at模式:添加内容

  • rb 或 wb

    在读取二进制数据的时候,字节字符串和文本字符串的语义差异可能会导致一个潜在的陷阱。 特别需要注意的是,索引和迭代动作返回的是字节的值而不是字节字符串

    1
    2
    3
    4
    5
    6
    >>> t = 'Hello World'
    >>> t[0]
    'H'
    >>> b = b'Hello World'
    >>> b[0]
    72
  • 换行符

    在Unix和Windows中是不一样的(分别是 \n 和 \r\n )。 默认情况下,Python会以统一模式处理换行符。 这种模式下,在读取文本的时候,Python可以识别所有的普通换行符并将其转换为单个 \n 字符。 类似的,在输出时会将换行符 \n 转换为系统默认的换行符。 如果你不希望这种默认的处理方式,可以给 open() 函数传入参数 newline=''

  • 错误处理:errors=

    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>> # Replace bad chars with Unicode U+fffd replacement char
    >>> f = open('sample.txt', 'rt', encoding='ascii', errors='replace')
    >>> f.read()
    'Spicy Jalape?o!'
    >>> # Ignore bad chars entirely
    >>> g = open('sample.txt', 'rt', encoding='ascii', errors='ignore')
    >>> g.read()
    'Spicy Jalapeo!'
    >>>

3. print

1
2
3
4
5
6
with open('d:/work/test.txt', 'wt') as f:
print('Hello World!', file=f)

>>> print('ACME', 50, 91.5, sep=',', end='!!\n')
ACME,50,91.5!!
>>>

4. 文件不存在才能写入

1
2
3
4
>>> import os
>>> if not os.path.exists('somefile'):
... with open('somefile', 'wt') as f:
... f.write('Hello\n')

5. 模拟文件

io.StringIO()和io.BytesIO()

1
2
3
4
5
>>> s = io.StringIO()
>>> s.write('Hello World\n')
12
>>> print('This is a test', file=s)
15
  • Cookbook
  • Program Language
  • Python
  • Cookbook
python垃圾回收
Python厨书笔记-5
  1. 1. 1. 文件IO
    1. 1.1. 2. with
    2. 1.2. 3. print
    3. 1.3. 4. 文件不存在才能写入
    4. 1.4. 5. 模拟文件
© 2024 何决云 载入天数...