Python文件操作

153 阅读1分钟

只读

read_only = open(file, 'r', encoding='utf-8') 参数:

  1. file: 文件路径
  2. r: 只读
  3. encoding: 指定解码器, Windows下不指定utf-8会报gbk错误.

注意: 类似于encoding的有确定名字的参数, 需要放在最后, 这似乎是对所有api都一样的规矩.

read

一次性读取所有内容:

print(read_only.read())

readlines

一次行读取所有行, 存在列表里, 通过for遍历.

readline

一次读一行, 读后指针指向下一行, 直到末尾.

可写

writable = open(file, 'w', encoding='utf-8') 注意:

  1. 这是会清空文件内容的
  2. 需要close()后才能在系统资源管理器等软件中看到写入效果.

追加

appendable = open(file, 'a', encoding='utf-8')

练习

写入数字

将生日1998 02 07写入文件birthday.txt

path = 'birthday.txt'
file = open(path, 'w', encoding='utf-8')
year, month, day = 1998, 02, 07
file.write('{year} {month} {day}'.format(year=year, month=month, day=day))

笔记: 无论写入的数字还是什么, 最终在文件里面都是字符串.

读取数字

将生日从文件中读取出来.

file = open(path, 'r', encoding='utf-8')
line = file.readline()  # 实际上得到的是字符串
nums = line.split(' ')  # 去除空格, 得到一个由单个数字字符组成的列表
result = [int(num) for num in nums]  # 将字符串格式的数字转换为真正的数字存储在result列表中