从数据库中读取数据后,我想返回数据并将其写入CSV文件。如何使用多进程进行操作?
def get_data():
data = get_data_from_database() #a dataframe
data.to_csv('data.csv', index=False) #step 1: write to csv file
return data #step 2: return data
如何使用多处理执行步骤1和步骤2?
您是指多线程吗?如果是,那么如果您想将其写入文件,则应使用锁,它可能会在代码中变成痛苦!
但是,如果您不担心可以做这样的事情
import threading
def thread_write(data):
data.to_csv('data.csv', index=False) # step 1: write to csv file
def get_data():
data = get_data_from_database() #a dataframe
t = threading.Thread(target=thread_write, args=(data,)) #pass your function as target of thread, and it's input variables as a tuple to args
t.start()
return data # step 2: return data
尝试这个;
def get_data():
data = []
data = get_data_from_database() #a dataframe
if len(data) >0:
for i in range (len(data)):
data[i].to_csv('data.csv', index=False) #step 1: write to csv file
return data #step 2: return data