python文件操作
import os
1、简单的写
# 不占内存修改文件
old_file = '作文.txt'
new_file = '作文.txt.new'
f = open(old_file, "r")
f_new = open(new_file, "w")
old_str = "happy"
new_str = "happiness"
for line in f:
print(line)
if "happy" in line:
line = line.replace(old_str, new_str)
f_new.write(line)
f.close()
f_new.close()
2、文件重命名
# os.rename(new_file, old_file)
os.replace(new_file, old_file) # 把新文件名字改成原文件 的名字,就把之前的覆盖掉了
3、whith的用法
# with open("作文.txt", "r") as f:
# data = f.read()
# print(data)
"""
with语句可以在代码块执行完毕后还原进入该代码块时的现场,包含有with语句的代码块的执行过程如下:
1)计算表达式的值,返回一个上下文管理对象;
2)加载上下文管理器对象的__exit__()方法以备后用;
3)调用上下文管理器对象的__enter__()方法;
4)如果with语句中设置了目标对象,则将__enter__()方法的返回值赋值给目标对象;
5)执行with中的代码块;
6)如果步骤5中代码正常结束,调用上下文管理器对象的__exit__()方法,其返回值直接忽略;
7)如果步骤5中代码执行过程中发生异常,调用上下文管理器的__exit__()方法,并将异常类型、值及traceback信息作为参数传递给
__exit__()方法。如果__exit__()返回值为false,则异常会被重新抛出;如果其返回值为true,,异常被挂起,程序继续执行。
"""