python基础(四)——读写文件

#_*_ coding: utf-8 _*_
#写文件,先以w的格式打开文件(w即write,写),再writelines()写文件
f = open("c:/Users/47864/Desktop/2.txt", "w")
f.writelines("read success\n" + "lkzlso")
f.close()
print("write success!")
#读文件,直接open文件,再readlines()
f = open("c:/Users/47864/Desktop/2.txt")
while True:
    content = f.readlines()
    if not content:
        break
    for line in content:
        print(line.strip())
#以a的格式打开文件(a即append,追加),再追加进文件
f = open("c:/Users/47864/Desktop/2.txt", "a")
f.write("\nappend\n")
f.close()
#读文件
f = open("c:/Users/47864/Desktop/2.txt")
while True:
    content = f.readlines()
    if not content:
        break
    for line in content:
        print(line.strip()) 

输出结果:

write success!
read success
lkzlso
read success
lkzlso
append

猜你喜欢

转载自blog.csdn.net/ax478/article/details/79849909