开发者

How to bring a list from a text file into python

I have a list of lists in a text file, when I read it into python, how do I assign it to a variable as a list rather then a string?

writing to text file:

file1 = open("contacts.txt", "w")
file1.write(str(contact_list))

inside of the text file:

[['Name', 'Email', 'Phone Numbe开发者_Go百科r'], ['Name1', 'Email1', 'Phone Number1']]
file1 = open("contacts.txt", "r")
contact_list = file1.readline().rstrip()
print(contact_list[0])

Treated like a string ^

When I try to print index 0 from the list it treats it like a string


If you have a text file that contains a list of lists, you can use the ast.literal_eval function from the ast module in Python to parse the string and return a list. This function will evaluate the string as a literal Python expression, which in this case should be a list of lists.

Here is an example:

import ast

# Read the text file and assign the contents to a variable
with open('my_file.txt', 'r') as f:
    contents = f.read()

# Use ast.literal_eval to parse the string and return a list
my_list = ast.literal_eval(contents)

# Print the type of the resulting object to verify that it is a list
print(type(my_list))

This code will read the contents of the text file and use ast.literal_eval to parse the string and return a list. The type of the resulting object will be printed, which should be list. You can then use the my_list variable to access the list of lists in your code.


You saved a string representation of the list. If the values of the list are all python literals (string, int, float, etc...), then you can have python parse them again

import ast
with open("contacts.txt") as file1:
    contact_list = ast.literal_eval(file1.read())
print(contact_list[0])

Alternately, you could save in another format such as JSON or even a python pickle file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜