1

I have a names.txt file that is a list of names, each name is on a new line:

   'Fred',
   'Ed',
   'George'

I want to open my txt file, extract the names and add it to a list with nice looking formatting. When I try

    list=[]
    names = open(names.txt)
    for s in names:
        display(s)
        list.append(s)

The output looks like the below

    "     'Fred',/n"
    "     'Ed',/n"
    "     'George',/n"

Naturally I get a list, but I want my list to be list = ['Fred','Ed','George'] not with the /n, "" and extra spaces. Does anyone know the best way to get rid of the extra white space and the /n line. I could take 2-3 steps to replace everything, but does anyone know if there is a better way?

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
user3782816
  • 131
  • 1
  • 1
  • 8

4 Answers4

2

If you are sure the format is as you describe in the question, you can use ast.literal_eval:

from ast import literal_eval

data = literal_eval('[' + open('your_file.txt', 'r').read() + ']')

print(data)

Prints:

['Fred', 'Ed', 'George']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

Atypical use for pandas, but this is basically comma-separated values:

In[0]:
import pandas as pd

df = pd.read_csv('names.txt', header=None)

ls = df[0].str.strip().str.replace("'",'').to_list()
ls

Out[0]:

['Fred', 'Ed', 'George']

str.strip() to remove whitespace and then str.replace() to remove the extra single quotes

Tom
  • 8,310
  • 2
  • 16
  • 36
0

Will this help:

with open('names.txt','r') as f:
    
    lst = f.readlines()

lst = [l.strip()[:-1].strip("'") for l in lst]

print(lst)
print('\n'.join(lst))

Output:

['Fred', 'Ed', 'George']
Fred
Ed
George
Red
  • 26,798
  • 7
  • 36
  • 58
0

No need to use Pandas for this, you can just do:

with open('names.txt', 'r') as f:
    data = f.read()

names = [name.strip("', ") for name in data.splitlines()]
PApostol
  • 2,152
  • 2
  • 11
  • 21