python文件

打开文件r

# 打开文件
file = open(r"E:\helloworld.txt", "r")
# 读取文件(如果不存在,报错)
txt = file.read()
# 打印文件
print(txt)
# 关闭文件
file.close()

写文件w

# 写入文件(不存在创建文件,存在则覆盖文件)
file = open(r"E:\a.txt", "w")
# 追加内容
file.write("hello python")
# 关闭文件
file.close()

追加写文件a

# 写入文件(不存在创建文件,存在在文件后面追加内容)
file = open(r"E:\b.txt", "a")
# 追加内容
file.write("hello python\n")
# 关闭文件
file.close()

打开文件指定字符集(读取中文)

# 打开文件
file = open(r"E:\简历.txt", "r", encoding="utf8")
# 读取文件(如果不存在,报错)
txt = file.read()
# 打印文件
print(txt)
# 关闭文件
file.close()

改文件内容

file = open(r"E:\b.txt", "r")
txt = file.read()
a = txt.replace("python", "world")
file.close()
file = open(r"E:\\b.txt", "w")
file.write(a)
file.close()

复制文件

# 打开文件
file = open(r"E:/a.txt", "r")
# 读取文件(若不存在文件报错)
txt = file.read()
# 关闭文件
file.close()
# 打开文件
file = open(r"E:/b.txt", "w")
# 写入文件(若不存在,则新建文件,若存在则覆盖文件)
file.write(txt)
# 关闭文件
file.close()

合并文件

# 打开文件
file = open(r"E:/a.txt", "r")
# 读取文件(若不存在文件报错)
a = file.read()
# 关闭文件
file.close()
# 打开文件
file = open(r"E:/b.txt", "r")
# 读取文件(若不存在文件报错)
b = file.read()
# 关闭文件
file.close()
# 打开文件
file = open(r"E:/c.txt", "w")
# 读取文件(若不存在文件报错)
c = file.write(a + b)
# 关闭文件
file.close()

执行读取每一行文件内容

# 打开文件
file = open(r"E:/a.txt", "r")
while True:
    txt = file.readline()
    if txt == "":
        break
    print(txt, end="")
file.close()

读取偶数行文件内容

# 打开文件
file = open(r"E:/a.txt", "r")
index = 1
while True:
    txt = file.readline()
    if txt == "":
        break
    if index % 2 == 0:
        print(txt, end="")
    index += 1
file.close()

readlines读取文件所有行返回的是一个列表

# 打开文件
file = open(r"E:/a.txt", "r")
list1 = file.readlines()
for n in list1:
    print(n, end="")
file.close()

找出文件最大值与最小值之差,注意文件读取的内容为字符串,需要转换为int类型

file = open(r"E:/a.txt", "r")
list1 = []
while True:
    txt = file.readline()
    if txt == "":
        break
    list1.append(int(txt))
file.close()
print(max(list1) - min(list1))

原理:如果是长得比较像数字的字符串比较大小,先比较字符串的第一个字符即5>2>1

withopen语法 

with open(r"E:/a.txt", "r") as f:
    txt = f.read()
print(txt)
f.close()

写Json文件dump(ensure_ascii=False)表示不转义中文字符

import json

dict1 = {"name": "刘备", "age": 18, "sex": "男"}
file = open("data.json", "w", encoding="utf8")
json.dump(dict1, file, ensure_ascii=False)  # 转义中文字符
file.close()

读取Json文件load(file)

import json

file = open(r"a.json", "r", encoding="utf8")  # 把json文件内容转化为python字典
data = json.load(file)
file.close()
print(data)
for i in data:
    print(i, data[i])

修改json文件内容

import json

file = open(r"data.json", "r", encoding="utf8")
dict1 = json.load(file)
file.close()
dict1["age"] = 30
file = open(r"data.json", "w", encoding="utf8")
json.dump(dict1, file, ensure_ascii=False)
file.close()

打开文件,读取文件内容转化为字典,关闭文件,修改字典内容,打开文件,写入文件,关闭文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值