Saving files to different folder
Question:
I´m trying to save converted excel files from different paths, to the same folder.
How can I pass the path to the function correctly?
Now what is happening is that it is attaching the original path to the save path I have given to the function.
So my solution was:
import pandas as pd
import glob
import csv, json
import openpyxl
from pathlib import Path
import os, os.path
import errno
destination_path = "C:\csv_files"
all_paths = [r"C:\PLM\PML.xlsx",r"C:\TMR\TMR.xlsx",r"C:\PLM\PLM.xlsx"]
Create variable to store tuple list
all_items = []
Create tuple list with file path and file name without extension
def getFileName():
for paths in all_paths:
all_items.append((paths , paths.split("\")[-1].split(".")[0]))
Convert given files by iterating through tuple list and pass destination folder.
def convertFiles():
for item in all_items:
read_file = pd.read_excel(item[0], 'Relatório - DADOS', index_col=None, engine='openpyxl')
read_file.to_csv(destination_path + "\"+ item[1] + ".csv", encoding='utf-8', index=False)
Answers:
You can ensure the save folder exists by adding this line before the outer for
loop:
Path(save_path).mkdir(exist_ok=True)
See documentation.
I´m trying to save converted excel files from different paths, to the same folder.
How can I pass the path to the function correctly?
Now what is happening is that it is attaching the original path to the save path I have given to the function.
So my solution was:
import pandas as pd
import glob
import csv, json
import openpyxl
from pathlib import Path
import os, os.path
import errno
destination_path = "C:\csv_files"
all_paths = [r"C:\PLM\PML.xlsx",r"C:\TMR\TMR.xlsx",r"C:\PLM\PLM.xlsx"]
Create variable to store tuple list
all_items = []
Create tuple list with file path and file name without extension
def getFileName():
for paths in all_paths:
all_items.append((paths , paths.split("\")[-1].split(".")[0]))
Convert given files by iterating through tuple list and pass destination folder.
def convertFiles():
for item in all_items:
read_file = pd.read_excel(item[0], 'Relatório - DADOS', index_col=None, engine='openpyxl')
read_file.to_csv(destination_path + "\"+ item[1] + ".csv", encoding='utf-8', index=False)
You can ensure the save folder exists by adding this line before the outer for
loop:
Path(save_path).mkdir(exist_ok=True)
See documentation.