简体   繁体   English

从.txt文件python读取列表

[英]read lists from .txt file python

I want to create .txt which contains several lists我想创建包含多个列表的 .txt

a = ['210','210','210','210']
b = ['0.3','0.3','0.3','0.3']
c = ['7.85e-06','7.85e-06','7.85e-06','7.85e-06']

with open("abcd.txt", "w") as output:
    output.write(str(a))
    
with open("abcd.txt", "a") as output:
    output.write(str(b))
    
with open("abcd.txt", "a") as output:
    output.write(str(c))

So test file is generated like所以测试文件是这样生成的

['210', '210', '210', '210']['0.3', '0.3', '0.3', '0.3']['7.85e-06', '7.85e-06', '7.85e-06', '7.85e-06']

Now I want to extract the first element of all lists.现在我想提取所有列表的第一个元素。 How can I do that?我怎样才能做到这一点? Here each list contain 4 elements but it may be higher that also.这里每个列表包含 4 个元素,但也可能更高。

You can use .index() to find the position of ']' and .count() to find how many of them you have:您可以使用.index()找到的“]”和位置.count()找到你有多少人有:

with open('abcd.txt', 'r') as input:
    content = input.read()


strings = []
start = 0
for _ in range(content.count(']')):
    end = content.index(']', start) + 1
    strings.append(content[start:end]
    start = end

for string in strings:
    print(string[1:string.index(',')])

The second argument to .index() tells it from which position to start searching from, in order to avoid returning always the position of the first ']'. .index()的第二个参数告诉它从哪个位置开始搜索,以避免总是返回第一个 ']' 的位置。

Output:输出:

'210'
'0.3'
'7.85e-06'

However, if you are going to store data in a file, I suggest you do it in something a bit more structured like JSON which every language has a parser for.但是,如果您打算将数据存储在文件中,我建议您使用更结构化的方式进行操作,例如 JSON,每种语言都有一个解析器。

firstly read the file and store the data in a variable.首先读取文件并将数据存储在变量中。

with open('abcd.txt','r') as myFile:
    data = myFile.read()

then remove the first and last square brackets because they are not needed.然后删除第一个和最后一个方括号,因为它们不需要。

data = data[1:-1]

then split the data from '][' because this is where two lists meet.然后从 '][' 拆分数据,因为这是两个列表相遇的地方。

lists=data.split("][")

then get the first values of all elements and store it in another list like:然后获取所有元素的第一个值并将其存储在另一个列表中,例如:

firstelements = []
for aList in lists:
    firstelements.append(aList.split(",")[0])

If you can work with json (why not??) - here is a json based solution如果您可以使用 json(为什么不可以??) - 这是一个基于 json 的解决方案

import json

a = ['210', '210', '210', '210']
b = ['0.3', '0.3', '0.3', '0.3']
c = ['7.85e-06', '7.85e-06', '7.85e-06', '7.85e-06']

data = {'a': a, 'b': b, 'c': c}

# save to a json file
with open('data.json', 'w') as f:
    json.dump(data, f)

# read from json file and get the data you need
with open('data.json') as f:
    data = json.load(f)
first_values = [x[0] for x in data.values()]
print(first_values)

output输出

['210', '0.3', '7.85e-06']

Here is another solution using regex ,这是使用regex另一种解决方案,

Regex Demo

import re
from ast import literal_eval

with open('abcd.txt', "r") as f:
    for x in re.findall(r".+?\]", f.read()):
        print(literal_eval(x)[0])

210
0.3
7.85e-06

You can concatenate strings using the + operator.您可以使用+运算符连接字符串。 Try this:尝试这个:

a = ['210','210','210','210']
b = ['0.3','0.3','0.3','0.3']
c = ['7.85e-06','7.85e-06','7.85e-06','7.85e-06']

to_save = str(a) + str(b) + str(c)
with open("abcd.txt", "wb") as output:
    output.write(to_save)

If you want to duplicate the code it might be better to write it as a function.如果您想复制代码,最好将其编写为函数。

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

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