python读取txt文件

如何读取文件内容?

file = open('致橡树.txt', 'r', encoding='utf-8')
print(file.read())
file.close()

按行读取

import time

file = open('致橡树.txt', 'r', encoding='utf-8')
for line in file:
    print(line, end='')
    time.sleep(0.5)
file.close()

file = open('致橡树.txt', 'r', encoding='utf-8')
lines = file.readlines()
for line in lines:
    print(line, end='')
    time.sleep(0.5)
file.close()

如何修改文件或者在文件末尾添加新内容?

lines = ['标题:《致橡树》', '作者:舒婷', '时间:1977年3月']
file = open('致橡树.txt', 'a', encoding='utf-8')
#a 表示append 在文件末尾添加元素;w表示write,直接覆盖之前的内容
for line in lines:
    file.write(f'\n{line}')
file.close()

如何阐述文件报错的流程?

file = None
try:
    file = open('致橡树.txt', 'r', encoding='utf-8')
    print(file.read())
except FileNotFoundError:
    print('无法打开指定的文件!')
except LookupError:
    print('指定了未知的编码!')
except UnicodeDecodeError:
    print('读取文件时解码错误!')
finally:
    if file:
        file.close()

else里放 没报错时执行的语句

如何省略finally里的文件关闭操作

try:
    with open('致橡树.txt', 'r', encoding='utf-8') as file:
        print(file.read())
except FileNotFoundError:
    print('无法打开指定的文件!')
except LookupError:
    print('指定了未知的编码!')
except UnicodeDecodeError:
    print('读取文件时解码错误!')

并不是所有的对象都可以放在with上下文语法中,只有符合上下文管理器协议(有__enter__和__exit__魔术方法)的对象才能使用这种语法

如何在占用少量内存的情况下将一个文件内容写入到另一个文件内容

try:
    with open('a.jpg', 'rb') as file1, \
        open('b.png', 'wb') as file2:
        data = file1.read(512)
        while data:
            file2.write(data)
            data = file1.read()
except FileNotFoundError:
    print('指定的文件无法打开.')
except IOError:
    print('读写文件时出现错误.')
print('程序执行结束.')

如何将字典对象保存为json文件

json:“javascript object notation”
json可跨平台,因为使用的是纯文本格式

import json

my_dict = {
    'name': '骆昊',
    'age': 40,
    'friends': ['王大锤', '白元芳'],
    'cars': [
        {'brand': 'BMW', 'max_speed': 240},
        {'brand': 'Audi', 'max_speed': 280},
        {'brand': 'Benz', 'max_speed': 280}
    ]
}
with open('data.json', 'w') as file:
    json.dump(my_dict, file)
print('字典已经保存到data.json文件中')

中文是用Unicode编码书写的,因此会显示为编码形式

如何读取json文件保存为字典?

import json

with open('data.json', 'r') as file:
    my_dict = json.load(file)
    print(type(my_dict))
    print(my_dict)

附:json的四个重要函数

json模块有四个比较重要的函数,分别是:

dump - 将Python对象按照JSON格式序列化到文件中
dumps - 将Python对象处理成JSON格式的字符串
load - 将文件中的JSON数据反序列化成对象
loads - 将字符串的内容反序列化成Python对象

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值