Home > Software design >  Import a list of pairs into python
Import a list of pairs into python

Time:05-27

I have a file of the form:

{{ 1 , string1 }
 { 2 , string2 }
 ...
 { 1000 , string1000}}

The first field is always an integer and the second is a string (they can contain spaces). I would like to import this into Python (as a list of lists). What's the easiest way to achieve this? If it requires minor editing of the file that's fine (eg replacing the {braces} with [brackets] etc).

CodePudding user response:

You can try re module (maybe it needs minor adjustments - depending on exact structure of file):

import re

out = []
with open("your_file.txt", "r") as f_in:
    for n, s in re.findall(
        r"(\d )\s*,\s*(.*?)\s*\}\}?$", f_in.read(), flags=re.M
    ):
        out.append([int(n), s])

print(out)

Prints:

[[1, "string1"], [2, "string2"], [1000, "string1000"]]

CodePudding user response:

If you can easily remove all the braces at the start and end of the lines then you can use the csv module:

import csv

with open("list.csv") as csvfile:
            rows = csv.reader(csvfile)
            res = list(rows)

(PS to mods: should I delete this question? I went to do so but because it has an answer I got a warning that deleting answered questions could get me blocked.)

  • Related