Using df.to_csv() with the keyword argument compression='gzip' should produce a gzip archive. I tested it using same keyword arguments as you, and it worked.
You may need to upgrade pandas, as gzip was not implemented until version 0.17.1, but trying to use it on prior versions will not raise an error, and just produce a regular csv. You can determine your current version of pandas by looking at the output of pd.__version__.
Using df.to_csv() with the keyword argument compression='gzip' should produce a gzip archive. I tested it using same keyword arguments as you, and it worked.
You may need to upgrade pandas, as gzip was not implemented until version 0.17.1, but trying to use it on prior versions will not raise an error, and just produce a regular csv. You can determine your current version of pandas by looking at the output of pd.__version__.
It is done very easily with pandas
import pandas as pd
Write a pandas dataframe to disc as gunzip compressed csv
df.to_csv('dfsavename.csv.gz', compression='gzip')
Read from disc
df = pd.read_csv('dfsavename.csv.gz', compression='gzip')
Hi All,
I am a beginner with Python trying to solve a few problems with my daily workflow in a non-tech job. I recently wrote a script that I feel could use some improvement, but I am not knowledgeable enough to know how to make it more efficient.
Background: I sometimes need to download multiple large compressed .txt.gz files from our server and convert them into .csv before I offload them to other business units for review. Instead of extracting manually and pasting into Excel, I wanted to write a script to take care of it. Here is what I came up with after some YouTube and StackOverflow searching (the delimiter in these txt files is a '|' instead of the standard ',':
import csv
import shutil
import gzip
import os
src_dir = 'C:\\Users\\user\\Downloads\\'
dest_dir = 'C:\\Users\\user\\Desktop\\Python\\extractedgzs\\'
f_names = []
# get file names
for files in os.listdir(src_dir):
if files.endswith('.txt.gz'):
f_names.append(files)
#file found confirmation
print('found these files:')
print(f_names)
# unzip gz file to dest dir
for name in f_names:
with gzip.open(src_dir+name, 'rb') as f_in:
with open(dest_dir+name[0:-6], 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# extracted file to .csv
with open(dest_dir+name[0:-6], 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split("|") for line in stripped if line)
with open(dest_dir+name[0:-6]+'csv', 'w', newline='') as out_file:
writer = csv.writer(out_file)
writer.writerows(lines)I understand that this code is rather rigid but that it is fine since I am the only person who will ever use it and it only needs to serve this one purpose.
The main issue I have with this is that I generate an text file that is used up by the splitter/csv writer for writing the csv. I was wondering if there is any way to eliminate this step, or at the very least automate deleting that file once all the csv's are written.
I appreciate any tips you can offer!
csv - Using csvreader against a gzipped file in Python - Stack Overflow
reading gzipped csv file in python 3 - Stack Overflow
Compressing CSV to GZIP and writing to SharePoint
How do I use CSV Writers with GZIP files in Python 3? - Stack Overflow
Use the gzip module:
with gzip.open(filename, mode='rt') as f:
reader = csv.reader(f)
#...
I've tried the above version for writing and reading and it didn't work in Python 3.3 due to "bytes" error. However, after some trial and error I could get the following to work. Maybe it also helps others:
import csv
import gzip
import io
with gzip.open("test.gz", "w") as file:
writer = csv.writer(io.TextIOWrapper(file, newline="", write_through=True))
writer.writerow([1, 2, 3])
writer.writerow([4, 5, 6])
with gzip.open("test.gz", "r") as file:
reader = csv.reader(io.TextIOWrapper(file, newline=""))
print(list(reader))
As amohr suggests, the following works as well:
import gzip, csv
with gzip.open("test.gz", "wt", newline="") as file:
writer = csv.writer(file)
writer.writerow([1, 2, 3])
writer.writerow([4, 5, 6])
with gzip.open("test.gz", "rt", newline="") as file:
reader = csv.reader(file)
print(list(reader))
Default mode for gzip.open is rb, if you wish to work with strs, you have to specify it extra:
f = gzip.open(filename, mode="rt")
OT: it is a good practice to write I/O operations in a with block:
with gzip.open(filename, mode="rt") as f:
You are opening the file in binary mode (which is the default for gzip).
Try instead:
import gzip
import csv
f = gzip.open(filename, mode='rt')
csvobj = csv.reader(f,delimiter = ',',quotechar="'")
Pretty much what you've already done, except read_csv also has nrows where you can specify the number of rows you want from the data set.
Additionally, to prevent the errors you were getting, you can set error_bad_lines to False. You'll still get warnings (if that bothers you, set warn_bad_lines to False as well). These are there to indicate inconsistency in how your dataset is filled out.
import pandas as pd
data = pd.read_csv('google-us-data.csv.gz', nrows=100, compression='gzip',
error_bad_lines=False)
print(data)
You can easily do something similar with the csv built-in library, but it'll require a for loop to iterate over the data, has shown in other examples.
I think you could do something like this (from the gzip module examples)
import gzip
with gzip.open('/home/joe/file.txt.gz', 'rb') as f:
header = f.readline()
# Read lines any way you want now.