Home > other >  Python Script saves files one directory above user input directory
Python Script saves files one directory above user input directory

Time:09-23

I am writing a python script which uses tkinter to take the user input for a .xlsx file and segregate the data present it it by grouping the data by location and then exporting individual csv files for each unique value of location alongside the columns I tell it to keep. The issue with it is while taking the user input for the directory to store the files in, the script is saving the file one directory above it.

Ex- lets say the user selects the directory for the files to be saved in as \Desktop\XYZ\Test, the script is saving the exported file one directory above it i.e. \Desktop\XYZ while adding the name for the subdirectory Test into the exported file name. The code I'm using is attached below. This is probably a simple issue but being a newbie I'm at my wits end trying to resolve this so any help is appreciated.

Code:

import pandas as pd
import csv
import locale
import os
import sys
import unicodedata
import tkinter as tk
from tkinter import simpledialog
from tkinter.filedialog import askopenfilename
from tkinter import *
from tkinter import ttk

ROOT = tk.Tk()

ROOT.withdraw()
    
data_df = pd.read_excel(askopenfilename())
grouped_df = data_df.groupby('LOCATION')

folderpath = filedialog.askdirectory()

for data in grouped_df.LOCATION:
    grouped_df.get_group(data[0]).to_csv(folderpath data[0] ".csv",encoding='utf-8', mode='w ')
    filename =data[0]
    f=pd.read_csv(folderpath filename ".csv", sep=',')
    #print f
    keep_col = ['ID','NAME','DATA1','DATA4']
    new_f = f[keep_col]
    new_f.to_csv(folderpath data[0] ".csv", index=False)

Sample data

enter image description here

P.S- There will be data is DATA3 and DATA 4 columns but I just didn't enter it here

How the Script is giving the output: Notice it added the directory name test into the file name and saved it one directory above

Thanks in Advance!

CodePudding user response:

It seems like the return value of filedialog.askdirectory() ends with the folder the uses selected without a trailing slash, i.e: \Desktop\XYZ\Test

You're full path created by folderpath data[0] ".csv" with an example value for data[0] of "potato" will be \Desktop\XYZ\Testpotato.csv

You need to at least append the \ manualy

for data in grouped_df.LOCATION:
    grouped_df.get_group(data[0]).to_csv(folderpath "\\" data[0] ".csv",encoding='utf-8', mode='w ')
    filename =data[0]
  • Related