文件操作
文件读取
def print_file_info(file_name):
f = None
try:
f = open(file_name, "r", encoding = "utf-8")
print(type(f)) # # <class '_io.TextIOWrapper'>
except Exception as reason:
print("open file fail")
else: # 如果未抛出异常会进入else
print(f.read()) #读取文件并打印
finally: # 该部分都会执行
if f:
f.close()
f = open("C:/Users/sewerperson/Desktop/intro.cpp","r",encoding = "UTF-8")
print(f.read(2)) #读取n个字符
print(f.readline(5)) # 读取当前行的字符, 若超过当前行字符, 则读取下一行
print(f.readline()) #默认读取当前行所有字符
print(f.readlines(1)) # 读取 n 行封装至列表内, 无参数则把文件每一行都封装 ['\\name\n']
for i in f:
print(i)
print(f.read()) #续着上次未读完的继续
f.close() #关闭文件
with open("C:/Users/sewerperson/Desktop/intro.cpp", "r", encoding = "utf=8") as f:
print(f.readlines())
print(f.read()) # ValueError: I/O operation on closed file.
文件的写操作
f=open("C:/Users/sewerperson/Desktop/intro.cpp", "w", encoding = "utf-8") # 如果存在直接覆盖, 不存在就新建
f.write("add") # write 并没有真正写入硬盘中, 而是放置于缓冲区
f.flush() # 直到调用 flush() 或 close() 时, 缓冲区中的内容才真正写入
f.close()
with open("C:/Users/sewerperson/Desktop/intro.cpp", "a", encoding= "utf-8") as f: # 追加
f.write("new")
案例
count = 0
with open("C:/Users/sewerperson/Desktop/intro.cpp", "r", encoding = "utf-8") as f:
for line in f:
w = line.split(" ")
print(w)
for i in w:
if i == "the":
count += 1
print(f"the出现的次数是{count}")
with open("C:/Users/sewerperson/Desktop/intro.cpp", "r",encoding = "UTF-8") as f:
k = f.read()
p = k.split(" ")
print(p.count("the"))
with open("C:/Users/sewerperson/Desktop/intro.cpp","r",encoding="utf-8") as f:
for line in f:
line.strip()
g = open("xxx.txt", "a", encoding = "utf-8")
g.write(f"{line}")
f = open("C:/Users/sewerperson/Desktop/intro.cpp", "r", encoding = "UTF-8")
data=f.read()
data=data.replace("replace me",'')
data=data[:-2] #略去后两个字符