# -*- coding: utf-8 -*-标签:文件,utf,encoding,python,菜鸟,print,line,txt,open From: https://www.cnblogs.com/liyuzhoupan/p/16599411.html
import sys, time
# 读文件:一次性读取所有内容
#r=read
f = open("singe.txt", 'r', encoding="utf-8").read()
print(f)
# 写文件,覆盖原来的文件
# w=write
f1 = open("singe1.txt", 'w', encoding="utf-8")
f1.write("my name is liyuzhoupan \n")
f1.write("welcome 123!!!")
f1.close()
# 追加模式
# a=append
f2 = open("singe2.txt", 'a', encoding="utf-8")
f2.write("jiushizhegewenjian\n")
f2.close()
# 读取前5行,readline()读取一行
f4 = open("singe.txt", 'r', encoding="utf-8")
for i in range(5):
print(f4.readline()) # 按行读取
f4.close()
print("f5".center(50, "*"))
# 循环读取所有,readlines(),一次性读所有行
f5 = open("singe.txt", 'r', encoding="utf-8")
for line in f5.readlines():
if line != " ":
print(line.strip())
f5.close()
print("f6".center(50, "*"))
# 不打印第N行
f6 = open("singe.txt", 'r', encoding="utf-8")
for index, line in enumerate(f6.readlines()):
if index == 9:
print("我是第9行".center(50, "-"))
continue
print(line.strip())
# 循环读取==高效读取方法
f7 = open("singe.txt", 'r', encoding="utf-8")
count = 0
for line in f7:
if count == 9:
print(line)
print("我是{count}行".format(count=count).center(20, "*"))
count += 1
continue
print(line)
count += 1
# 记录当前位置
f7 = open("singe.txt", 'r', encoding="utf-8")
print("--------------------")
print(f7.readline())
print(f7.tell())
print(f7.seek(10))
# print(f7.readline())
f7.close()
# 刷写文件
f8 = open("singe.txt", 'a', encoding="utf-8")
f8.write("hello liyuzhou pan\n")
f8.flush()
f8.close()
# 文件读写
f9 = open("singe.txt", 'r+', encoding="utf-8")
print(f9.readline())
print(f9.readline())
print(f9.readline())
f9.write("ddddddddddddddddddddddddd00")
f9.close()
# 【二进制文件读】
f10 = open("singe.txt", 'rb')
print(f10.readline())
print(f10.readline())
print(f10.readline())
f10.close()
# 【二进制文件写】
f11 = open("singe.txt", 'ab')
f11.write("liyuzhou".encode())
f10.close()
# 【文件修改】
file_tmp = open("singe.txt.tmp", 'w', encoding="utf-8")
with open("singe.txt", 'r', encoding="utf-8") as file:
for line in file:
if "披上红妆" in line:
file_tmp.write("幻想就**********披上红妆\n")
elif line == "\n":
print("******")
else:
file_tmp.write(line)
file_tmp.close()