python3基础之文件对象操作

本文介绍了Python中文件的基本操作,包括文件的打开、读取、写入及关闭等方法,并展示了如何使用with语句简化文件操作流程。此外,还详细解释了JSON数据格式的编码与解码过程。

1.向文本文件中写入内容

s = 'Hello world\n文本文件的读取方法\n文本文件的写入方法\n'
# 需要写入文件的字符串
print('显示需要写入的内容:\n{0:s}'.format(s))
#-----文件操作开始------------
f = open('sample.txt', 'a+')  # 以追加(a)和读写(+)的模式打开并创建文件对象f
f.write(s) # 对文件对象f使用write方法
f.close()  # 关闭文件
#-----文件操作结束------------
显示需要写入的内容:
Hello world
文本文件的读取方法
文本文件的写入方法

使用上下文管理关键字with方法

s = 'Hello world\n文本文件的读取方法\n文本文件的写入方法\n'
with open('sample.txt', 'a+') as f:
    f.write(s)
with open('sample.txt','r') as src, open('sample_new.txt', 'w') as dst:
    dst.write(src.read())
with open('sample_new.txt', 'r') as fp:
    for line in fp:
        print(line)
第一个文件操作案例。Hello world

文本文件的读取方法

文本文件的写入方法

Hello world

文本文件的读取方法

文本文件的写入方法
fp.closed
True

2.读取文件内容

fr = open('sample.txt', 'r')
print(fr.read(4))
xxx的
print(fr.read(18))
第一个文件操作案例。Hello wo
print(fr.read())
rld
文本文件的读取方法
文本文件的写入方法
Hello world
文本文件的读取方法
文本文件的写入方法
fr.close()
fr.closed
True

3.JSON知识点学习

import json
x = ['yu','bright','1','4','5']
x_bianma = json.dumps(x) # 利用json的dumps对列表x进行字符串编码操作
x_bianma
'["yu", "bright", "1", "4", "5"]'
x_jiema = json.loads(x_bianma)
x_jiema == x # 解码后与x相同类型
True
x_bianma == x # 编码后与x不同类型
False
f_ = open('sample.txt', 'w')
json.dump({'a':1,'b':2,'c':3}, f_) # 对字典进行编码并写入文件
f_.close()

4.读取并显示文件所有内容

with open('sample.txt', 'r') as fp:
    while True:
        line = fp.readline()
        if not line:
            break
        print(line)
{"a": 1, "b": 2, "c": 3}
with open('sample_new.txt', 'r') as fp:
    for line in fp:
        print(line)
第一个文件操作案例。Hello world

文本文件的读取方法

文本文件的写入方法

Hello world

文本文件的读取方法

文本文件的写入方法
with open('sample_new.txt','r') as fp:
    lines = fp.readlines()   # 操作大文件是不建议这样使用
    print(''.join(lines))
第一个文件操作案例。Hello world
文本文件的读取方法
文本文件的写入方法
Hello world
文本文件的读取方法
文本文件的写入方法

5.移动文件指针

fp = open('sample_new.txt','r+')
fp.tell()  # 返回指针当前位置
0
fp.read(20) # 读取20个字符
'第一个文件操作案例。Hello '
fp.seek(13)  #重新定位文件指针的位置
13
fp.write('测试')
fp.seek(0)
0
fp.read()
'测试文件操作案例。Hello world\n文本文件的读取方法\n文本文件的写入方法\nHello world\n文本文件的读取方法\n文本文件的写入方法\n'
fp.close()

转载于:https://www.cnblogs.com/brightyuxl/p/9099387.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值