MisterY
MisterY

Reputation: 57

Add column to dataframe if file exists

I have a dataframe and I would like to add new columns if a file exists.

This is my approach:

files = 'input/'
if files.endswith('txt') and 'text' in files:
    df['A'] = 'blah'
    df['B'] = 'Test'
    df['C'] = 'Test2'
else:
    pass

but there's nothing added to "df". What's the problem?

Edit: Thx to Aravind G. this is the solution:

files = 'input/'
data = [x for x in os.listdir(files) if x .endswith('txt') and 'text' in x]
if len(data) > 0:
   df['A'] = 'blah'
   df['B'] = 'Test'
   df['C'] = 'Test2'
else:
   pass

Upvotes: 0

Views: 108

Answers (1)

Aravind G.
Aravind G.

Reputation: 431

files is a string defined by you, which does not end with 'txt'. That's why it never adds anything to df.

To check if a file with given filename exists, you could use glob.

If you want to check if a file exists in the given directory with given specifications, you could simply do this -

files_list = [f for f in glob('input/*') if 'text' in f]
if len(files_list) > 0:
    df['A'] = 'blah'
    df['B'] = 'Test'
    df['C'] = 'Test2'
else:
    pass

Upvotes: 1

Related Questions