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
  • 112,593
  • 23
  • 157
  • 280

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
  • 118,151
  • 13
  • 38
  • 75
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
  • 63,514
  • 5
  • 71
  • 101
0

You can use the split method:

with open('euler22.txt') as f:
    name_list = f.read().split(",")
Abhigyan Jaiswal
  • 2,217
  • 2
  • 7
  • 26