I have a set of files I need to clean and save into one excel file. I want the sheet names in the finished Excel file to be the same as the file names. I was able to get the file names and save the data into each sheet in an earlier version of my code but Iām having trouble adding the file name as the sheet name.
writer = pd.ExcelWriter('Data.xlsx')
df_list= []
dir_b = r'/Desktop/MyProjects'
sheet_tabs = []
file_names = os.listdir(dir_b)
for line in file_names:
if not line.startswith('.'):
if re.search('\.csv', line):
string = line.split('.')[0]
sheet_tabs.append(string)
for csv in sorted(Path(dir_b).glob('*.csv')):
df = pd.read_csv(csv)
df.rename(columns = lambda x: x.strip(), inplace = True)
car_column = df.pop('car')
df.insert(9, 'car', car_column)
df.drop_duplicates(keep = 'first', inplace = True)
df_list.append(df)
df_dict = dict.fromkeys(sheet_tabs, df_list)
for key, values in df_dict.items():
values.to_excel(writer, sheet_name = key, index = False)
writer.save()