【python入门】python基础10——文件读写操作,open read write close,with方法

文件读写:

open(‘ xxx ')

open(‘ xxx’,'w')

.read()

.write()

.close()

最后一定要关闭文件,不然可能会有问题,存在数据丢失

法1:

with open('a.txt','w') as f:

    f.write('abc')

法2:

txt = open('a.txt','w')

try:

    txt.write('abc'+'\n')

except Exception:

    print('error')

finally:

    txt.close()




txt = open('./data/a.txt')

txt_read = txt.read()

print(txt_read)

txt.close()

txt = open('a.txt')
txt_lines = txt.readlines()
print(txt_lines)
for line in txt_lines:
    print(line)

txt.close()


txt = open('a.txt','w') ##覆盖
txt.write('jintian qianqi bucuo \n')
txt.write('hhhhhhhhhhhhhhhhhhhh \n')
txt.close()
txt = open('a.txt')
txt_read = txt.read()
print(txt_read)

txt.close()


txt = open('a.txt','a')  ##追加
txt.write('jintian qianqi bucuo \n')
txt.write('hhhhhhhhhhhhhhhhhhhh \n')
txt.close()
txt = open('a.txt')
txt_read = txt.read()
print(txt_read)
txt.close()

猜你喜欢

转载自blog.csdn.net/qq1518572311/article/details/80395815
今日推荐