0

In my code I have a list called euler22.txt:

with open('euler22.txt') as f:
    name_list = f.read().splitlines()

euler22.text is a long file, but I'll post the first 5 values in it:

"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH"

As you can see, it's structured as a list, but when I run the code the way I have it, it says that the length of name_list is only 1 - whereas I want it to be 500 (the length of the list). How can I make my code open this file as a list that is the length of how it's structured in the file?

martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

0

You can use csv module to load the data to a list:

import csv

data = []
with open('<your file.txt>', 'r') as f_in:
    reader = csv.reader(f_in, delimiter=',', quotechar='"')
    for line in reader:
        data.extend(line)
print(data)

Prints:

['MARY', 'PATRICIA', 'LINDA', 'BARBARA', 'ELIZABETH']

Or:

If the data is only on one line you can try to use ast.literal_eval:

from ast import literal_eval
data = literal_eval('[' + open('<your file.txt>', 'r').read() + ']')
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

The file looks like a CSV with many columns and just one row. You can use the csv module to parse it.

>>> import csv
>>> with open('euler22.txt') as fp:
...     names = next(csv.reader(fp))
... 
>>> names
['MARY', 'PATRICIA', 'LINDA', 'BARBARA', 'ELIZABETH']
>>> len(names)
5
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

You can use the split method:

with open('euler22.txt') as f:
    name_list = f.read().split(",")
abhigyanj
  • 2,355
  • 2
  • 9
  • 29