-2

Importing a txt file into Python and create a dataframe. In this process would like to use the filename (excluding the extension i.e. ".txt") in creating the dataframe having part of filename as its name. E.g. IF we importing "Conversion.txt" into python, would like the output dataframe to be created with name "Conversion".

user3738411
  • 75
  • 1
  • 6
  • Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – DarrylG Sep 20 '20 at 11:48

1 Answers1

0

You can do it with globals() (even though it's not considered a good practice in general). For example for all your csv files in your directory:

import os

l=[i for in os.listdir() if i[-3:]=='csv']
m=[i.split(sep='.')[0] for i in l]

for i in m: 
    globals()[i]=pd.read_csv(i+'.csv') #you can replace Conversion with any other filename

You can do the same for other file extensions (txt, xlsx, etc)

IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
  • Above one, we seem to have assigned manually the name but would like to have the name extracted from filename and used to name the dataframe. Helps in dealing with muiple file import scenarios where dataframes can be automatically named based on their filename. – user3738411 Sep 20 '20 at 12:11
  • Updated so that it will work with all files in the directory – IoaTzimas Sep 20 '20 at 15:34