[Python] Read txt file

Use a python script to read the txt file: in
this example, the txt content is 1,1,1;


with open('./task.txt') as f:
    lst = f.read()
# 使用 with 方法读取文件时,可以不用在读取后再 close 文件;   

print(lst)
print(type(lst))
# 1,1,1
# <class 'str'>
# 默认将 txt 内容作为字符串读取

lst = eval(lst)
print(lst)
print(type(lst))
# (1, 1, 1)
# <class 'tuple'>
# 使用 eval() 方法将 "1,1,1" 转化为元组 (1,1,1)

lst = list(lst)
print(lst)
print(type(lst))
# [1, 1, 1]
# <class 'list'>
# 使用 list() 方法将元组 (1,1,1) 转化为列表 [1,1,1]

Guess you like

Origin blog.csdn.net/ao1886/article/details/110388330