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,294
  • 3
  • 12
  • 31
user3782816
  • 121
  • 1
  • 1
  • 7

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
  • 118,151
  • 13
  • 38
  • 75
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
  • 7,322
  • 2
  • 12
  • 30
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
Ann Zen
  • 25,080
  • 7
  • 31
  • 51
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
  • 1,644
  • 2
  • 8
  • 15