I'd like to assign unique variable name with each file from a directory. I have no idea how this can be done. I'm new to python, so I'm sorry is the code is scruffy.
def DataFinder(path, extension):
import os
count = 0
extensions = ['.txt','.csv','.xls','xlsm','xlsx']
allfiles = []
if not extension in extensions:
print('Can\'t read data from this file type.\n','Allowed file types are\n',str(extensions))
else:
#loop through the files
for root, dirs, files in os.walk(path):
for file in files:
#check if the file ends with the extension
if file.endswith(extension):
count+=1
print(str(count)+': '+file)
allfiles.append(file)
if count==0:
print('There are no files with',extension,'extension in this folder.')
return allfiles
How this code be modified to assign variable name like df_number.of.file with each iteration as a string?
Thanks
My ultimate goal is to have set of DataFrame objects for each file under unique variable name without a need to create those variables manually.
The suggested duplicate did not answer my question, neither worked for me.
allfiles = {}
#filter through required data extensions
if not extension in extensions:
print('Can\'t read data from this file type.\n','Allowed file types are\n',str(extensions))
else:
#loop through the files
for root, dirs, files in os.walk(path):
for file in files:
#check if the file ends with the extension
if file.endswith(extension):
#raise counter
count+=1
print(str(count)+': '+file)
allfiles.update({'df'+str(count) : path+file})
After adjusting the code as suggested my output was a dictionary:
{'df1': 'C:/Users/Bartek/Downloads/First.csv', 'df2': 'C:/Users/Bartek/Downloads/Second.csv', 'df3': 'C:/Users/Bartek/Downloads/Third.csv'}
I achieved similar thing previously using list:
['df_1First.csv', 'df_2Second.csv', 'df_3Third.csv']
But my exact question is how to achieve this:
for each object in dict: -create a variable with consecutive object number
so this variable(s) can be passed as data argument to pandas.DataFrame()
I know this is very bad idea (http://stupidpythonideas.blogspot.co.uk/2013/05/why-you-dont-want-to-dynamically-create.html), therefore can you please show me proper way using dict?
Many thanks