user3782816
user3782816

Reputation: 171

Pandas how to import a txt file as a list

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?

Upvotes: 1

Views: 862

Answers (4)

PApostol
PApostol

Reputation: 2292

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()]

Upvotes: 0

Tom
Tom

Reputation: 8790

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

Upvotes: 1

Red
Red

Reputation: 27577

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

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195478

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']

Upvotes: 2

Related Questions