python3: 文件与IO

时间:2023-03-08 20:32:14

1.读写文本数据

# Write chunks of text data
with open('somefile.txt', 'wt') as f:
f.write(text1) # Redirected print statement
with open('somefile.txt', 'wt') as f:
print(line1, file=f) '''
文件的读写操作默认使用系统编码,可以通过调用 sys.getdefaultencoding() 来得到。 在大多数机器上面都是utf-8编码
'''
f = open('sample.txt', 'rt', encoding='utf-8')

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

# Read with disabled newline translation
with open('somefile.txt', 'rt', newline='') as f:
...

2. 打印输出至文件

with open('d:/work/test.txt', 'wt') as f:
print('Hello World!', file=f)

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

使用在 print() 函数中使用 sep 和 end 关键字参数,  改变默认的分隔符或者行尾符

>>> print('ACME', 50, 91.5)
ACME 50 91.5
>>> print('ACME', 50, 91.5, sep=',')
ACME,50,91.5
>>> print('ACME', 50, 91.5, sep=',', end='!!\n')
ACME,50,91.5!!
>>> #end参数也可以在输出中禁止换行。
>>> for i in range(3):
... print(i)
...
0
1
2 >>> for i in range(3):
... print(i, end=' ')
...
0 1 2 >>>
#str.join()也可以控制分隔符
>>> print(','.join(('ACME','','91.5')))
ACME,50,91.5
>>>
>>> row = ('ACME', 50, 91.5)
>>> print(','.join(row))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 1: expected str instance, int found
>>> print(','.join(str(x) for x in row))
ACME,50,91.5
>>> >>> print(*row, sep=',')
ACME,50,91.5
>>>

4. 读写字节文件(如:比如图片,声音文件等等)

5.文件不存在才能写入

6. 字符串IO操作

7.读写压缩文件

8.固定大小记录的文件迭代

9.读取二进制数据到可变缓冲区中[文件对象的readinto()]

和普通 read() 方法不同的是, readinto() 填充已存在的缓冲区而不是为新对象重新分配内存再返回它们。 因此,你可以使用它来避免大量的内存分配操作

11.文件路径名的操作[os.path]

12.测试文件是否存在

13.获取文件夹中的文件列表[os.listdir()]

pyfiles = [name for name in os.listdir('somedir')
if name.endswith('.py')]

对于文件名的匹配,你可能会考虑使用 glob 或 fnmatch 模块。比如:

import glob
pyfiles = glob.glob('somedir/*.py') from fnmatch import fnmatch
pyfiles = [name for name in os.listdir('somedir')
if fnmatch(name, '*.py')]

如果你还想获取目录中实体名列表的元信息,比如文件大小,修改时间等等, 你或许还需要使用到 os.path 模块中的函数或着 os.stat() 函数来收集数据。

14. 忽略文件名编码