使用python读取txt文件内容

写法一

open()打开某个文件

  ‘r’表示读取文件

  encoding='utf-8'表示以utf-8编码读取

readlines()会将每一行都读取出来

close()关闭该文件,每次操作完文件之后都要记得close()

f = open('D:\test.txt','r',encoding='utf-8')
text = f.readlines()
print(text)
f.close

 写法二

with open('D:\test.txt','r',encoding='utf-8') as f:
    text = f.readlines()
    print(text)

 结果是一样的,但是这种写法会比较好

原文地址:https://www.cnblogs.com/cyx-b/p/12864039.html