使用Python多重处理apply_async写入csv会导致数据丢失

时间:2019-02-19 14:22:26

标签: python csv multiprocessing

我有一个csv文件,在其中逐行读取url以对每个点进行请求。解析每个请求,并将数据写入output.csv。这个过程是并行的。

问题与书面数据有关。数据的某些部分被部分丢失或完全丢失(空白行)。我想这是由于异步进程之间的冲突或冲突而发生的。你能建议如何解决这个问题吗?

def parse_data(url, line_num):
    print line_num, url
    r = requests.get(url)
    htmltext = r.text.encode("utf-8")
    pois = re.findall(re.compile('<pois>(.+?)</pois>'), htmltext)
    for poi in pois:
        write_data(poi)

def write_data(poi):
    with open('output.csv', 'ab') as resfile:
        writer = csv.writer(resfile)
        writer.writerow([poi])
    resfile.close()

def main():
    pool = Pool(processes=4)

    with open("input.csv", "rb") as f:
        reader = csv.reader(f)
        for line_num, line in enumerate(reader):
            url = line[0]
            pool.apply_async(parse_data, args=(url, line_num))

    pool.close()
    pool.join()

2 个答案:

答案 0 :(得分:0)

尝试添加文件锁定:

import fcntl

def write_data(poi):
    with open('output.csv', 'ab') as resfile:
        writer = csv.writer(resfile)
        fcntl.flock(resfile, fcntl.LOCK_EX)
        writer.writerow([poi])
        fcntl.flock(resfile, fcntl.LOCK_UN)
     # Note that you dont have to close the file. The 'with' will take care of it

答案 1 :(得分:0)

并发写入同一文件确实是导致数据丢失/文件损坏的已知原因。此处的安全解决方案是“映射/缩小”模式-每个进程都将其写入自己的结果文件(映射),然后将这些文件连接在一起(缩减)。