0

I want to create .txt which contains several lists

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.

Adirio
  • 5,040
  • 1
  • 14
  • 26
Aakash Patel
  • 111
  • 7

5 Answers5

1

You can use .index() to find the position of ']' and .count() to find how many of them you have:

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 ']'.

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.

Adirio
  • 5,040
  • 1
  • 14
  • 26
1

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])
Nalin Angrish
  • 317
  • 5
  • 17
1

If you can work with json (why not??) - here is a json based solution

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']
balderman
  • 22,927
  • 7
  • 34
  • 52
0

Here is another solution using 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
sushanth
  • 8,275
  • 3
  • 17
  • 28
  • `eval`, or in this case `ast.literal_eval` is the reason why I think storing as plain text is not a very good idea. Now anyone can edit the file, place some python code ending in `#]` to trigger your pattern and that code will be run. I know that `eval` is the easiest way to parse a list which would require a lof of string parsing but that's the main reason why formats like CSV and JSON already have their parsers in the standard library so that you can store them in a file and retrieve them later without the need to `eval` potentially malicious code. – Adirio Sep 09 '20 at 06:38
-1

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.

  • This is not an answer, you suggested an improvement on part of the code he provided but the question was about reading not about writing. Not trying to sound too harsh. – Adirio Sep 09 '20 at 06:11