# 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: ...
with open('d:/work/test.txt', 'wt') as f: print('Hello World!', file=f)
使用在 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','50','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 >>>
5.文件不存在才能写入编码
6. 字符串IO操做spa
7.读写压缩文件code
8.固定大小记录的文件迭代对象
9.读取二进制数据到可变缓冲区中[文件对象的readinto()]blog
和普通 read()
方法不一样的是, readinto()
填充已存在的缓冲区而不是为新对象从新分配内存再返回它们。 所以,你能够使用它来避免大量的内存分配操做图片
11.文件路径名的操做[os.path]内存
12.测试文件是否存在utf-8
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()
函数来收集数据。