蓝绝

博客园 首页 新随笔 联系 订阅 管理

#读取文件内容

f=open('note.txt','r',encoding='utf-8')  #有中文使用encoding='utf-8'
text=f.readlines()
print(text)
f.close()

#推荐的使用的方式 with...as 上下文管理器
with  open('note.txt','r',encoding='utf-8') as f:
    print(f.readlines())
#运行输出
['helloworld\n', '我们你好啊我很好大家好\n', '我喜欢Python']
['helloworld\n', '我们你好啊我很好大家好\n', '我喜欢Python']

#写入,追加

#写文件中写入内容    打开模式  'r'表示是读取  'w'表示是写入  'a' 表示追加写入
with open('a.txt','a',encoding='utf-8')   as  file:
    file.write('你好啊')
    file.write('我很好')
    file.write('大家好\n')
    file.write('我喜欢Python')

  

posted on 2022-10-20 21:39  蓝绝  阅读(39)  评论(0)    收藏  举报