简体   繁体   English

Python将文本文件中的列表作为列表导入

[英]Python import list from text file as list

[2, 'hello', 3, 'good'] - is stored in myfile.txt on one line


 with open(myfile,'r') as f:
        myList = f.readlines()

but when I try to retrieve the first index, so "2' by using myList[0], the first square brackets is retrieved. 但是,当我尝试检索第一个索引时,使用myList [0]则为“ 2”,则检索了第一个方括号。

How can I set the imported line into a list? 如何将导入的行设置为列表?

use the ast module to convert the string to a list object 使用ast模块将字符串转换为列表对象

Ex: 例如:

import ast
with open(myfile,'r') as f:
        data= f.read()
        myList = ast.literal_eval(data)

.readlines() method reads lines of text from file, separated with the new line character and returns a list, containing those lines, so that's not the case. .readlines()方法从文件中读取文本行,并用换行符分隔,并返回包含这些行的列表,因此并非如此。

You could have read the contents of the file and eval it like this: 您可能已经阅读了文件的内容并对其进行评估,如下所示:

with open(myfile,'r') as f:
    my_list = eval(f.read())

Note, that the usage of eval is considered to be a really bad practice, as it allows to execute any python code written in the file. 注意,使用eval被认为是一种非常糟糕的做法,因为它允许执行文件中编写的所有python代码。

You can use the json module for this (since a list is a valid json object): 您可以为此使用json模块(因为列表是有效的json对象):

import json
with open(myfile) as f:
    myList = json.load(f)

您可以这样做:mylist = mylist [1:-1] .split(“,”)[1:-1]删除了括号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM