0
点赞
收藏
分享

微信扫一扫

python文件操作的几种方法with open,r,w,b

佛贝鲁先生 2022-01-27 阅读 95

“”"
python文件操作的几种方法:

读:r,rb,r+,r+b
写:w,wb,w+,w+b
加:a,ab,a+,a+b
tell():获取光标的位置
seek:调整光标的位置
flush:强制刷新
“”"

f = open(“中国.txt”,encoding = “utf-8”,mode = “r”)
content = f.read()
print(content)
f.close()

read(n)按照字符去读
f = open(“中国.txt”,encoding = “utf-8”,mode = “r”)
content = f.read(4)
print(content)
f.close()

readline()一行一行读
f = open(“中国.txt”,encoding = “utf-8”,mode = “r”)
content = f.readline()
print(content)
f.close()

readlines()返回一个列表,列表的每个元素就是每行
f = open(“中国.txt”,encoding = “utf-8”,mode = “r”)
content = f.readlines()
print(content)
f.close()

for读取
f = open(“中国.txt”,encoding = “utf-8”,mode = “r”)
for line in f:
print(line)
f.close(

#rb操作非文本的文件
f = open(“1.jpg”, mode=“rb”)
c = f.read()
f.close()
f1 = open(“2.jpg”, mode=“wb”)
f1.write©
f1.close()

w 文件的读 如果文件存在先清空原内容,再写入新内容

f = open(“小人本.txt”,encoding = “utf-8”,mode = “w”)
f.write(“垃圾日本”)
f.close()

wb操作非文本
f = open(“1.jpg”, mode=“rb”)
c = f.read()
f.close()
f1 = open(“2.jpg”, mode=“wb”)
f1.write©
f1.close()

文件的追加a,ab,a+,a+b,没有文件,创建文件,追加内容,有文件在源文件的最后面加入内容
f = open(“荷花.txt”,encoding = “utf-8”,mode = “a”)
f.write(’\n大农送’)
f.close()

文件的读写r+,必须先读再加,顺寻不能错误
f = open(“中国.txt”,encoding = “utf-8”,mode = “r+”)
content = f.read()
print(content)
f.write("\n我爱中国1111")
f.close()

tell()获取光标的位置,先读再获取,单位:字节
f = open(“中国.txt”,encoding = “utf-8”,mode = “r+”)
print(f.tell())
content = f.read()
print(f.tell())
f.close()

seek调整光标的位置,tell获取光标的位置
f = open(“中国.txt”,encoding = “utf-8”,mode = “r+”)
f.seek(6)
content = f.read()
print(content)
print(f.seek(60))
print(f.tell())
f.close()

flush强制刷新
f = open(“中国.txt”,encoding = “utf-8”,mode = “r+”)
f.write(“adas”)
f.flush()
f.close()

with open不需要关闭文件,open需要否则会一直占用内存
with open (“中国.txt”,encoding = “utf-8”) as f :
print(f.read())
with open (“中国.txt”,encoding = “utf-8”) as f,
open (“荷花”,encoding = “utf-8”,mode = “w”) as f1:
print(f.read())
f1.write(“荷花真漂亮”)

import os
with open (“中国.txt”,encoding = “utf-8”,mode = “r”) as f,
open (“我爱中国.txt”,encoding = “utf-8”,mode = “w”) as f1:
content = f.read()
content1 = content.replace(“中国”,“美女”)
f1.write(content)
os.remove(“中国.txt”)
os.renames(“我爱中国.txt”,“中国.txt”)

import os
with open (“中国.txt”,encoding = “utf-8”,mode = “r+”) as f:
content = f.read()
content1 = content.replace(“中国”,“美女”)
f.write(content1)
print(content1)

import os
with open (“中国.txt”,encoding = “utf-8”,mode = “r”) as f,
open (“我爱中国.txt”,encoding = “utf-8”,mode = “w”) as f1:
for line in f:
new_line = line.replace(“美女”,“中国”)
f1.write(new_line)
os.remove(“中国.txt”)
os.renames(“我爱中国.txt”,“中国.txt”)

有关清空的内容
关闭文件,再次以w模式打开此文件时,才会清空原有内容
with open (“中国.txt”,encoding = “utf-8”,mode = “w”) as f:
for i in range(10):
f.write(“阿松大”)

举报

相关推荐

0 条评论