【问题标题】:How to change .csv.gz encoding to utf-8如何将 .csv.gz 编码更改为 utf-8
【发布时间】:2019-10-25 23:59:07
【问题描述】:

我想使用 R 或 Python 将 .csv.gz 文件转换为 utf-8 编码。我怎样才能直接做到这一点?我找不到任何全面的指南来说明如何执行此操作。

我最好的尝试是在 python 中使用csv.reader 读取 .csv.gz 文件:

csvFile = gzip.open('pracodawcy_20190611_5.csv.gz', 'rt', newline='')
reader = csv.reader(csvFile)

但后来如何用utf-8将其保存为csv?

【问题讨论】:

    标签: python r csv text encoding


    【解决方案1】:

    很容易,它把文件放在一个向量中:

    import gzip
    
    ### assuming the file is separated as you said
    with gzip.open('input_file.csv.gz', 'rt', newline='\n') as f:
        content = f.readlines()
    
    ### to print the vector content
    for v in content :
        print(v)
    
    ### to write to .csv.gz
    with gzip.open('output.csv.gz', 'wb') as f:
    for v in content :
        f.write(v.encode('utf-8'))
    

    如果 read() 或 for 太大,您也可以每行懒惰地打开它。这里和网络上有很多例子。

    【讨论】:

    • 好的,我知道如何打开,但是如何使用 utf-8 正确保存为 .csv.gz 格式?
    猜你喜欢
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 2010-10-29
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多