Python gzip-提取.csv.gz文件-内存错误

问题描述 投票:1回答:2

我试图编写脚本以从ftp服务器访问.csv.gz文件,并将内容写回到同一服务器上的.csv文件。只要文件小于100mb,此方法似乎就可以正常工作,否则它将失败,从而导致内存错误。我无法找到一种方法来提取.csv文件,因此它逐行读取文件内容(元组列表)并将其写入新文件。

是否有更有效的方法,甚至是直接从.csv.gz文件中提取.csv文件的方法?

def gz_unzipper():

    hostname = "servername"
    directory = "path"
    input_file = directory + "filename.csv.gz"
    output_file = directory + "filename.csv"
    ftp = FTP(hostname)
    ftp.login (username, password)
    ftp.cwd(directory)

    f = gzip.open(input_file, 'r')
    gz_content = f.read()

    lines=csv.reader(StringIO.StringIO(gz_content))

    output_file = open(output_file, 'w')

    for line in lines:
        line  = repr(line)[1:-1]
        line = line.replace("'","")
        line = line.replace(" ","")

        output_file.write(line + "\n") 

    output_file.close  
    f.close()
python memory gzip extraction memory-efficient
2个回答
2
投票
lazy,这意味着它们仅在需要时才读取数据。

尝试类似的操作(对不起,未经测试):

with gzip.open(input_file, 'r') as fin, open(output_file,'w') as fout: csv_reader = csv.reader(fin) csv_writer = csv.writer(fout) csv_writer.writerows(csv_reader)
© www.soinside.com 2019 - 2024. All rights reserved.