首页 > 代码库 > python修改文件

python修改文件

## 修改文件

with open("test.txt", "w+") as f:

    f.write("I am a dba.\n")

    f.write("I am a boy.\n")

    f.seek(0)

    print(f.read())

f = open("test.txt", "r")

with open("test.txt.bak", "w+") as f_n:

    for l in f:

        l = l.replace("dba", "developer")  # 对指定内容就行替换修改

        f_n.write(l)

    f_n.seek(0)

    print(f_n.read())

f.close()

if "test.txt" in os.listdir("."):

    os.remove("test.txt")

os.rename("test.txt.bak", "test.txt")


python修改文件