Need help with multiprocessing!
So, I've been building my code here that converts xlsx to csv and puts it into a temporary folder, then appends those files into a list which will be concatenated and (in the future) sent to a database. For now, this is the code I have working:
from pathlib import Path
from xlsx2csv import Xlsx2csv
import time
from pathlib import Path
import os
import glob
import pandas as pd
import shutil
start_time = round(time.time(), 2)
root_path = Path("C:/Teste")
files = Path(root_path).glob('*')
print("Creating a temporary folder...")
CSVFolder = "{}\\TempCSV".format(files)
CSVFolderLoc = glob.glob(CSVFolder)
directory = "TempCSV"
JoinTempPath = os.path.join(root_path, directory)
#Foldercreation gives an error if exists, so this code checks if it exists and deletes it
if os.path.isdir(JoinTempPath) == True:
print("--Removing existent Temporary CSV Directory--")
shutil.rmtree(JoinTempPath)
# Create the directory 'TempCSV' in 'parent_dir'
os.mkdir(JoinTempPath)
print("Directory '% s' created" % directory)
def func():
list = []
for file in files:
if file.suffix.lower() == '.xlsx':
print("Now converting '% s' file" % file)
#if it finds xlsx files, converts it to csv in the temporary folder
destFile = os.path.join(JoinTempPath, "{}.csv".format(file.stem))
print(destFile)
Xlsx2csv(file, outputencoding="utf-8").convert(destFile)
#appends those converted files into the empty list
for csvFile in destFile:
print(round(time.time() - start_time,2))
list.append(pd.read_csv(destFile, dtype='unicode'))
print(round(time.time() - start_time,2))
#concatenates (will be send to a database in the next version)
x = pd.concat(list)
print(round(time.time() - start_time,2))
#execute the function
func()
I need your help to improve the speed. I have been trying to implement Multiprocessing but I have failed. I've tried something like this but I saw nothing different happening:
import multiprocessing
(...)
if __name__ == '__main__':
p1 = multiprocessing.Process(target= func)
p2 = multiprocessing.Process(target= func)
p1.start()
p2.start()
p1.join()
p2.join()
Can you please help me implement multiprocessing or other solution for this loop to run in parallel?
I've also tried this:
if __name__ == '__main__':
processes=[]
num_processes= os.cpu_count() #nr of cpus to distribute workload
#create processes and assign a function for each process
for i in range(0, num_processes):
process = Process(target=func)
processes.append(Process)
#start all processes
for process in processes:
process.start()
for process in processes:
process.join()
But got this error:
Traceback (most recent call last):
File "c:\Users\CatarinaRibeiro\Desktop\DatabaseConfig\Main2.py", line 130, in <module>
process.start()
TypeError: BaseProcess.start() missing 1 required positional argument: 'self'