python对文件读取和写入操作

读文件

# read 全部读出来
f = open('123.txt', encoding='utf-8')
content = f.read()
print(content,type(content))
f.close()

# read(n) 按照字符个数读取
f = open('123.txt', encoding='utf-8')
content = f.read(5)
print(content)
f.close()

# readline() 读一行
f = open('123.txt', encoding='utf-8')
print(f.readline())
print(f.readline())
print(f.readline())
f.close()

# readlines() 返回一个列表,列表中的每个元素是源文件的每一行。
f = open('123.txt', encoding='utf-8')
l1 = f.readlines()
for line in l1:
    print(line)
    print(l1)
f.close()

写文件

# 没有文件,创建文件,写入内容
# 如果文件存在,先清空原文件内容,在写入新内容
f = open('123.txt',encoding='utf-8',mode='w')
f.write('hahahaha')
f.close()

文件追加

# 没有文件创建文件,追加内容
# 有文件,在原文件的最后面追加内容
f = open('123.txt',encoding='utf-8',mode='a')
f.write('hahaha')
f.close()

读写文件

# 如果想追加内容在末尾,必须先读后写,因为文件指针默认在开头,所以需要改变文件指针的位置
f = open('123.txt', encoding='utf-8', mode='r+')
content = f.read()
print(content)
f.write('123456789')
f.close()

文件操作的其他方法

f = open('123.txt', encoding='utf-8', mode='r+')
content = f.read()
print(content)
print(f.tell())  # tell 获取文件指针的位置 单位字节。
f.seek(7) # seek 调整光标的位置
f.flush() # flush 强制刷新
f.write('123456789')
f.close()

另一种操作文件方式

with open('123.txt',encoding='utf-8') as f1:
    print(f1.read())

# 还可以同时操作两个文件
with open('1.txt', encoding='utf-8') as f1,open('2.txt', encoding='utf-8', mode='w')as f2:
    print(f1.read())
    f2.write('qweasdqweasd')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值