文件操作

一、文件操作-读

# 打开文件
file = open(r"C:\Users\Administrator\Desktop\record.txt", "r")
# 读取文件
text = file.read()
# 显示文件内容
print(text)
# 关闭文件
file.close()
# 打开文件打开文件指定的字符集
# file = open(r"D:\project\testpy\文件操作.py", 'r', encoding="utf8")
# text = file.read()
# print(text)

二、文件操作-写

# 打开文件
# file = open(r"c:\file\temp\b.txt", "w")
# 追加写
# file = open(r"c:\file\temp\b.txt", "a")
# 写内容
# file.write("hello python")
# 读文件
# text = file.read()
# print(text)

# 关闭文件
# file.close()

# file = open(r"c:\file\temp\a.txt", "w")
# file.write("我爱你python,我爱你")
# file.close()

file = open(r"c:\file\temp\a.txt", 'r')

text = file.read()
text2 = text.replace("python", "world")
file.close()
file = open(r"c:\file\temp\a.txt", 'w')

file.write(text2)

print(text)

三、复制文件

file = open(r"D:\project\testpy\文件操作.py", 'r', encoding="utf8")
text = file.read()
file.close()
file = open(r"D:\project\testpy\合并文件.py", 'w', encoding="utf8")
file.write(text)
file.close()

四、合并文件

file = open(r"D:\project\testpy\1文件操作.py", 'r', encoding="utf8")
text_a = file.read()
file.close()

file = open(r"D:\project\testpy\2文件操作-写.py", 'r', encoding="utf8")
text_b = file.read()
file.close()


file = open(r"D:\project\testpy\3合并文件_结果.py", 'a', encoding="utf8")
file.write(text_a + text_b)
file.close()

合并文件-结果

file = open(r"c:\file\temp\a.txt", 'r')

text = file.read()
text2 = text.replace("python", "world")
file.close()
file = open(r"c:\file\temp\a.txt", 'w')

file.write(text2)

print(text)

五、readline按行读取文件、readlines

file = open(r"D:\project\testpy\文件.py", 'r', encoding="utf8")
index = 1
while True:
    txt = file.readline()
    if txt == "":
        break
    if index % 2 == 0:
        print(txt, end="")
    index += 1

file.close()

file = open(r"C:\file\a.txt", 'r')
list1 = file.readlines()
for n in list1:
    print(n,end="")
# print(text)

六、计算文件最大数字和最小数字的差01

file = open(r"C:\file\a.txt", 'r')
list1 = file.readlines()
max_num = int(list1[0])
min_num = int(list1[0])
for n in list1:
    if int(n) >= max_num:
        max_num = int(n)

    if int(n) <= min_num:
        min_num = int(n)
print(max_num)
print(min_num)
print(max_num - min_num)

计算文件最大数字和最小数字的差02

file = open(r"C:\file\a.txt", 'r')
list1 = []
while True:
    text = file.readline()
    if text == "":
        break
    list1.append(int(text))
print(max(list1))
print(min(list1))
print(max(list1) - min(list1))

七、字符串比较大小的原理

list1 = [2, 3, 15, 45]
list2 = ["2", "3", "15", "45"]
print(max(list1), min(list1))
print(max(list2), min(list2))

# 结果:
45 2
45 15

八、读json文件

import json
file = open(r"C:\file\temp.json", "r", encoding="utf-8")
data = json.load(file)
print(data)
file.close()
for n, b in data.items():
    print(n,b)

修改json文件内容

import json
file = open(r"c:\file\temp.json", "r", encoding="utf-8")
dict1 = json.load(file)
dict1["name"] = "曹操"
file.close()
file = open(r"c:\file\temp.json", "w", encoding="utf-8")
json.dump(dict1, file, ensure_ascii=False)
file.close()

你可能感兴趣的:(文件操作)