Here is what my current code looks like below,
ws = sh.worksheet('DATAFRAME')
df = pd.DataFrame(ws.get_all_records())
df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
from datetime import datetime
now_ = datetime.now().strftime('%b %d %y %H_%M_%S')
df.to_excel(('DATAFRAME' now_ '.xlsx'), index=False)
As you can see, the dataframe gets saved in a working directory as an excel file but is there a simple way to save the dataframe in a subfolder inside the working folder?
CodePudding user response:
This function checks if there is a subfolder in this case called "DATAFRAMES" if it doesn't exist it creates it and after that the file is saved inside that subfolder, I put the 'sys.path[0]' because of problems with the relative path among other errors
from datetime import datetime
import sys, os
now_ = datetime.now().strftime('%b %d %y %H_%M_%S')
address_file = sys.path[0] #actual diretory
try:
address_file = address_file.replace('\\','/') #string maintenance with directory
os.mkdir(f'{address_file}/DATAFRAMES/') #creating a subfolder
except FileExistsError: #if subfolder already exists
address_file = f'{address_file}/DATAFRAMES/'
df.to_excel((f'{address_file}DATAFRAME{now_}.xlsx'), index=False) #Saving the file inside the subfolder via the stored path
I also recommend using 'fstring', it's more readable and easier to move, Anyway I hope I helped