简体   繁体   English

从python文件中读取列表格式的数据

[英]Read list formatted data from file in python

I know this must be a simple question for you all.我知道这对你们所有人来说一定是一个简单的问题。 I have textfile with test cases written in below list format,我有以下面列表格式编写的测试用例的文本文件,

[["arg1", "arg2", "arg3"], "Fail"]

[["arg1", "arg2", "arg4"], "Pass"]

. . . . . .

And I want to read this file in a list such a that, I can print list1[1] => "Fail".我想在一个列表中读取这个文件,这样我就可以打印list1[1] => "Fail".

thanks for your help.谢谢你的帮助。

Assumptions假设

  • You have a .txt file.您有一个.txt文件。
  • Format of a line is [["arg1", "arg2", "arg3",...etc.], "Fail/Pass"]一行的格式是[["arg1", "arg2", "arg3",...etc.], "Fail/Pass"]

Approach is to use regex to find all text between double quotes and append to the list.方法是使用正则表达式查找双引号之间的所有文本并附加到列表中。 The last one is taken as "Fail/Pass" and rest of them are args.最后一个被视为“失败/通过”,其余的都是参数。

import re

result = []

with open('text.txt','r') as f:
    for line in f:
        match = re.findall("\"(.*?)\"",line.strip())
        result.append([match[:-1],match[-1]])

print(result)
print(result[0][0])
print(result[0][1])

Sample Input .txt file示例输入.txt文件

[["arg1", "arg2", "arg3","arg4"], "Fail"]
[["arg1", "arg2", "arg4"], "Pass"]

Output输出

[[['arg1', 'arg2', 'arg3', 'arg4'], 'Fail'], [['arg1', 'arg2', 'arg4'], 'Pass']]
['arg1', 'arg2', 'arg3', 'arg4']
Fail

Just use eval , its internal python function and you dont need libraries.只需使用 eval ,它的内部 python 函数,你不需要库。

Example:例子:

lists = []
line1 = '[["arg1", "arg2", "arg3"], "Fail"]'
line2 = '[["arg1", "arg2", "arg4"], "Pass"]'
# Evaluate Lines
exLine1 = eval(line1)
exLine2 = eval(line2)
# Append Lines to lists
lists.append(exLine1)
lists.append(exLine2)
# Testing Example of your use case
print(str(exLine1[1] == "Fail"))

Just Convert this example to for loop you are using and it will be fast and simple只需将此示例转换为您正在使用的 for 循环,它将快速而简单

You can use ast.literal_eval() to safe convert the string line to a python expression您可以使用ast.literal_eval()将字符串行安全地转换为 python 表达式

Example:例子:

import ast

with open('list.txt') as f:
    lines = f.readlines()

data = [ast.literal_eval(line) for line in lines]

for item in data:
    print(item[1])

I would do like this.我会这样做。

sample myfile.txt:示例 myfile.txt:

[["arg1", "arg2", "arg3"], "Fail"]
[["arg1", "arg2", "arg4"], "Pass"]

Main python file.主python文件。

file1 = open('myfile.txt', 'r') 
count = 0

while True: 
    count += 1

    # Get next line from file 
    list = file1.readline()
    if not list: 
        break
    #convert string to list
    res = list.strip('][').split(', ') 
    print(res[1])

After reading the file line by line, Convert the string of list into list by using split.逐行读取文件后,使用split将列表的字符串转换为列表。

You can hack together some pretty simple string manipulation code, as everyone is providing here.您可以编写一些非常简单的字符串操作代码,正如每个人都在此处提供的那样。 I've done it simply like this:我只是这样完成的:

text = """
[["arg1", "arg2", "arg3"], "Fail"]
[["arg1", "arg2", "arg4"], "Pass"]
"""

for line in text.strip().splitlines():
    line = line.replace('[', '')
    line = line.replace(']', '')
    print line.split(',')[-1].strip()

It's not pretty but you can do it plenty of better ways if you're looking to do this is production.它并不漂亮,但如果您希望在生产中做到这一点,您可以用很多更好的方法来做到这一点。

you can try something like below:您可以尝试以下操作:

with open("test.txt", "r") as test_file:
content = test_file.readlines()

print(content)
print(type(content))

for data in content:
    print(ast.literal_eval(data)[1])

print("*" * 30)
for i in range(1, len(content)+1):
    print(i)

output:输出:

index:  0

[["arg1", "arg2", "arg3"], "Fail"]

index: 1

[["arg1", "arg2", "arg4"], "Pass"]

1
2

What about this code example from link :来自链接的这个代码示例怎么样:

# load additional module
import pickle

with open('listfile.data', 'rb') as filehandle:
    # read the data as binary data stream
    placesList = pickle.load(filehandle)

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

相关问题 python从txt文件中读取格式化数据的快速方法 - python Quick way to read formatted data from txt file 当字典以某种方式格式化时,如何从文本文件中读取数据? [蟒蛇] - How to read back data from a text file when the dictionary is formatted in a certain way? [Python] 快速读取部分文件的格式化数据(Gmsh网格格式) - Read formatted data from part of a file fast (Gmsh mesh format) Python pandas从csv文件中读取列表数据类型中的列表 - Python pandas read list in list data type from csv file Python:如何从网络读取文件并从数据中列出清单? - Python: How to read file from web and make a list from the data? 如何从python中格式不规则的数据文件中提取数据 - How to extract data from an irregularly formatted data file in python 从格式类似于 Python 中的 JSON 文件的列表中提取值 - Extract value from a list formatted like a JSON file in Python 有没有办法在 Python 中按时间格式(小时:分钟:秒)从 excel 文件读取的数据执行数学运算(平均值和总和)? - Is there a way to perform math operations (average and sum) in Python on time formatted (hours:minutes:seconds) DATA read from an excel file? 从文件中读取python列表 - Read python list from a file 从python文件中读取错误的UTF数据列表,并将其与一行进行比较 - Read a list of bad UTF data from a file in python and compare it with a line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM