当前位置:   article > 正文

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

txt.close()

文件读写:

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()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/183102
推荐阅读
相关标签
  

闽ICP备14008679号