'pandas read_csv() method supports zip archive reading but not to_csv() method supports zip archive saving
Pandas 0.18 supports read_csv zip file as argument and reading zipped csv table correctly into data frame. But when i am trying to use to_csv() method to save data frame as zipped csv, i am getting error. According to official documentation, zip format not supported in to_csv() method. Any thoughts? Thank you.
import pandas as pd
works fine
data = pd.read_csv("E:\ASML SED.zip")
error out IOError: [Errno 2] No such file or directory: 'E:\ASML SED.zip'
data.to_csv("E:\ASML SED Zipped.zip", compression = 'zip')
Solution 1:[1]
Indeed, zip format not supported in to_csv() method according to this official documentation, the allowed values are ‘gzip’, ‘bz2’, ‘xz’.
If you really want the 'zip' format, you can try to save as uncompressed csv file, then using cli to compress the .csv file to .csv.zip.
Solution 2:[2]
I had the same issue trying to compress my csv to zip and this really worked for me. U can adapt it to your code
import zipfile
import tempfile
file_name = "Your_csv_file_name.csv"
with tempfile.NamedTemporaryFile(delete=False,suffix='.csv') as tempName:
df.to_csv(tempName.name)
with tempfile.NamedTemporaryFile(delete=False,suffix=".zip") as tempZip:
with zipfile.ZipFile(tempZip, mode='w', compression=zipfile.ZIP_DEFLATED) as zip_file:
zip_file.write(tempName.name, file_name)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Qikai |
Solution 2 | Oliver_Fragoso |