# 打开文件并只读文件
file = open(r"D:\file\test.txt","r") # 第一个r代表方式转义,第二个r代表只读操作,只读文件必须存在
# 读取文件
txt = file.read()
print(txt)
# 关闭文件,若不关闭文件则会消耗内存
file.close()
# * ***************************************************************
# 打开文件并写入内容
# 若文件不存在则新建文件,若文件存在则覆盖文件
file1 = open(r"D:\file\test.txt1","w")
# 写入内容
file1.write('hello world hahaha22221')
# 关闭文件
file1.close()
# ****************************************************************
# 打开文件并追加写入文件内容
# 若文件不存在则新建文件,若文件存在则在文件后追加内容
file2 = open(r"D:\file\test.txt2", "a")
# 写入内容
file2.write("this is a dog")
file2.write("wow\n") #换行
# 关闭文件
file2.close()
# ****************************************************************
# 打开文件指定字符集
# 若文件格式是utf-8,打开的时候需要指定字符集
file = open(r"D:\file\测试文档.txt","r",encoding='utf-8')
txt = file.read()
print(txt)
file.close()
# ****************************************************************
"""
练习案例
文件a.txt中为:我爱python
打开文件a.txt,将文件中的python换为world
"""
# 读取文件
doc = open(r"D:\file\a.txt","r")
text = doc.read()
# 替换字符,使用replace方法替换,若有替换次数限制可加上参数max,str.replace(old, new[, max])
a = text.replace("python","world")
doc.close() #以上是只读方式打开,必须关闭
# 写入方式打开,写入文件
doc = open(r"D:\file\a.txt","w")
doc.write(a)
doc.close()
# ****************************************************************
# 复制文件
# 读出来a文件
doc1 = open(r"D:\file\a.txt","r")
# 读到的a文件给变量text1
text1 = doc1.read()
doc1.close()
# 打开b文件写入a的值
doc2 = open(r"D:\file\b.txt","w")
text2 = doc2.write(text1)
doc2.close()
# ****************************************************************
# 合并文件
# 读出来a文件,读出来b文件,a+b写入c文件
doc3 = open(r"D:\file\a.txt","r")
# 读到的a文件给变量text1
text3 = doc3.read()
doc3.close()
# 打开b文件写入a的值
doc4 = open(r"D:\file\b.txt","r")
text4 = doc4.read()
doc4.close()
# 打开c文件写入a+b
doc5 = open(r"D:\file\c.txt","w")
doc5.write(text3 + text4)
doc5.close()
# ****************************************************************
# 按行读取文件内容,readline方法
# read会一次性把文件内容都读取放在内存中,消耗内存
doc = open(r"D:\file\a.txt","r")
text = doc.readline() # 读第一行
print(text,end='') #文本中自带回车,print也有换行功能,所以用end=‘’可以保证输出无多余空行
text = doc.readline() # 读第二行
print(text,end='')
# 可用while循环来输出文件内容,直到结束
while True:
text = doc.readline()
# 当读到最后一行时,页面会显示空行
if text == '':
break
print(text, end='')
print()
# ****************************************************************
# 在都是整数的文件a1中,取最大值和最小值的差
# 将文件中的每行整数作为一个列表的值,判断最大最小值取差
# 字符串比较大小时会先比较字符串的第一个数字的大小 如125和51比较大小 最大是52 最小是125
# 打开文件
doc = open(r"D:\file\a1.txt","r")
# 新建一个列表
list = []
while True:
# 将读到的文本赋予一个变量
text = doc.readline()
if text == '':
break
# 将读到的文本写入列表中,并且转为int类型以作比较
list.append(int(text))
doc.close()
# 计算列表中最大和最小值差
print(max(list) - min(list))
# ****************************************************************
# with open()语法,该语法不需要执行close()关闭,会自动关闭
with open(r"D:\file\a1.txt","r") as file:
txt = file.read()
print(txt)
python文件操作
最新推荐文章于 2021-12-11 11:50:43 发布