Python 中的文件 - 读取包含列表的文件
Files in Python - reading in a file with lists
我得到了一个文件,可以读入以下数据:
[420, True, "Hello", 6.9]
[["How", "are", "you"], False, {"chicken":"nuggets"}, 666]
.txt 中的每一行都包含在 []
.
中
newfile = open('file.txt', 'r')
lines = newfile.readlines()
all = []
for line in lines:
line = line.strip('\n')
line = line[1:-1]
line=line.split(', ')
all += [line]
cleaning_up = [item for row in all for item in row]
这似乎适用于我列表栏中的任何项目 ["How", "are", "you"]
,因为它被拆分为
["How",
"are",
"you"]
当我打印包含我所有数据的列表中的每一项时。有什么办法可以纠正这个问题,使整个列表保持为单个元素而不是三个?
您可以使用 ast
模块中的 literal_eval() 来解析包含 Python 数据结构的字符串。
例如
>>> import ast
>>> ast.literal_eval('[["How", "are", "you"], False, {"chicken":"nuggets"}, 666]')
[['How', 'are', 'you'], False, {'chicken': 'nuggets'}, 666]
所以,在你的循环中你可以做
for line in lines:
line = line.strip('\n')
all.append(ast.literal_eval(line))
您可以使用 eval 将字符串转换为列表。
newfile = open('file.txt', 'r')
lines = newfile.readlines()
all = []
for line in lines:
line = line.strip('\n')
line = eval(line)
all.append(line)
cleaning_up = [item for row in all for item in row]
我得到了一个文件,可以读入以下数据:
[420, True, "Hello", 6.9]
[["How", "are", "you"], False, {"chicken":"nuggets"}, 666]
.txt 中的每一行都包含在 []
.
newfile = open('file.txt', 'r')
lines = newfile.readlines()
all = []
for line in lines:
line = line.strip('\n')
line = line[1:-1]
line=line.split(', ')
all += [line]
cleaning_up = [item for row in all for item in row]
这似乎适用于我列表栏中的任何项目 ["How", "are", "you"]
,因为它被拆分为
["How",
"are",
"you"]
当我打印包含我所有数据的列表中的每一项时。有什么办法可以纠正这个问题,使整个列表保持为单个元素而不是三个?
您可以使用 ast
模块中的 literal_eval() 来解析包含 Python 数据结构的字符串。
例如
>>> import ast
>>> ast.literal_eval('[["How", "are", "you"], False, {"chicken":"nuggets"}, 666]')
[['How', 'are', 'you'], False, {'chicken': 'nuggets'}, 666]
所以,在你的循环中你可以做
for line in lines:
line = line.strip('\n')
all.append(ast.literal_eval(line))
您可以使用 eval 将字符串转换为列表。
newfile = open('file.txt', 'r')
lines = newfile.readlines()
all = []
for line in lines:
line = line.strip('\n')
line = eval(line)
all.append(line)
cleaning_up = [item for row in all for item in row]