Based on a given SQL-Statement, I extract from a database to CSV with thefollowing function:
def extract_from_db():
with open('myfile.csv','w') as outfile:
for row in cursor:
outfile.write(str(row[0])+";"+str(row[1])+";"+str(row[2])+";"+str(row[3])+";"+str(row[4])+";"+str(row[5])
+";"+str(row[6])+";"+str(row[7])+";"+str(row[8])+";"+str(row[9])+";"+str(row[10])+";"+str(row[11])+";"+str(row[12])
+";"+str(row[13])+";"+str(row[14])+"\n")
How can I write in the beginning of the file the column names for a variable amount of columns, so that I don't have to hardcode it? Also the hardcoded concatenation is pretty ugly.
You could use the description
desc = cursor.description
function. It returns a sequence of 7 item sequences and you can get the column names from
for seq in desc:
print seq[0]
I would also recommend using pandas to do your writing to csv.
Ebrahim Jackoet has already mentioned that you can use cursor.description to get the column names from your query. If you don't have a very large number of rows to process, though, the csv module is built in and makes writing rows simple. It also handles all of the necessary quoting
An example follows:
import csv
with open("myfile.csv", "w") as outfile:
writer = csv.writer(outfile, delimiter = ";")
for row in cursor:
writer.writerow(row)
Related
I'm doing some manipulation on a CSV file using Python and the csv module. I take a CSV file, do some operations, and output an XML file. Very simplified, but the input data looks similar to this:
name,group
joe,staff
jane,student
bill,staff
barry,support
jack,student
I have a list as follows:
outputList = ['staff', 'support']
Essentially, what I want to do is remove the line of data if the group field isn't contained in the outputList. So what I would end up with is:
name,group
joe,staff
bill,staff
barry,support
The main reason I need to remove the rows is because I then need to sort by outputList (which is a lot longer than in this example, and in a specific non-alphabetical order).
Doing the sorting is relatively easy:
csvData = sorted(csvData, key=lambda k: (outputList.index(k['group'])))
However, obviously without removing the rows that aren't needed I get an error that the group value isn't in the outputList.
Is there an easy way of removing the data, or do I just need to iterate over each row and check whether the value is present? I've seen methods of doing it when you just have two lists. E.G.
data = ['staff', 'support', 'student']
csvData = [data for data in csvData if data not in outputList]
There's no other way to filter the data without scanning all the data of course, you can simply do something like this:
import csv
def parser(fp, groups):
with open(fp) as fin:
reader = csv.reader(fp)
for row in reader:
if row[1] in groups:
yield row
csvData = parser('~/some_loc/file.csv', outputList)
Load your csv into a pandas dataframe df.
The you can use:
df = df[df.group.isin(outputList)]
Isin creates a boolean series(mask) which you can use to select only the relevant rows.
I have an array named genrelist that contains all the different genres of a movie. How do i write them out to the csv such that each element in the genrelist is in one cell and they are in a row instead of a column in Python 3.6?
Currently, i can write them out in a column by using this code:
with open('data.csv', 'a') as csvFile:
csvFileWriter = csv.writer(csvFile)
for genre in genrelist:
csvFileWriter.writerow([genre])
csvFile.close()
This will produce an output of:
|shonen|
|action|
|Adventure|
Desired output: |shonen| |action| |adventure|
The for loop writes the single genre to a row, like you desire, but you initiate a new row every single time! This makes the multiple rows seem like a column. Your desired output can be generated by printing the entire genreList with the writerow function. Like so:
with open('data.csv', 'a') as csvFile:
csvFileWriter = csv.writer(csvFile)
csvFileWriter.writerow(genreList)
csvFile.close()
The module pandas happens to have a really nice read_csv() function and also a df.to_csv function.
What you would do is create a dataframe like so:
import pandas as pd
df = pd.DataFrame(read_csv('data.csv'))
to change the columns to rows, just use:
df.transpose()
and then you can write it to a file like this:
df.to_csv('transposeddata.csv')
The full documentation can be found here:
Pandas Documentation
Started learning python after lots of ruby experience. With that context in mind:
I have a csv file that looks something like this:
city_names.csv
"abidjan","addis_ababa","adelaide","ahmedabad"
With the following python script I'd like to read this into a list:
city_names_reader.py
import csv
city_name_file = r"./city_names.csv"
with open(city_name_file, 'rb') as file:
reader = csv.reader(file)
city_name_list = list(reader)
print city_name_list
The result surprised me:
[['abidjan', 'addis_ababa', 'adelaide', 'ahmedabad']]
Any idea why I'm getting a nested list rather than a 4-element list? I must be overlooking something self-evident.
A CSV file represents a table of data. A table contains both columns and rows, like a spreadsheet. Each line in a CSV file is one row in the table. One row contains multiple columns, separated by ,
When you read a CSV file you get a list of rows. Each row is a list of columns.
If your file have only one row you can easily just read that row from the list:
city_name_list = city_name_list[0]
Usually each column represent some kind of data (think "column of email addresses"). Each row then represent a different object (think "one object per row, each row can have one email address"). You add more objects to the table by adding more rows.
It is not common with wide tables. Wide tables are those that grow by adding more columns instead of rows. In your case you have only one kind of data: city names. So you should have one column ("name"), with one row per city. To get city names from your file you could then read the first element from each row:
city_name_list = [row[0] for row in city_name_list]
In both cases you can flatten the list by using itertools.chain:
city_name_list = itertools.chain(city_name_list)
As others suggest, your file is not an idiomatic CSV file. You can simply do:
with open(city_name_file, "rb") as fp:
city_names_list = fp.read().split(",")
Based on comments, here is a possible solution:
import csv
city_name_file = r"./city_names.csv"
city_name_list = []
with open(city_name_file, 'rb') as file:
reader = csv.reader(file)
for item in reader:
city_name_list += item
print city_name_list
I'm "pseudo" creating a .bib file by reading a csv file and then following this structure writing down every thing including newline characters. It's a tedious process but it's a raw form on converting csv to .bib in python.
I'm using Pandas to read csv and write row by row, (and since it has special characters I'm using latin1 encoder) but I'm getting a huge problem: it only reads the first row. From the official documentation I'm using their method on reading row by row, which only gives me the first row (example 1):
row = next(df.iterrows())[1]
But if I remove the next() and [1] it gives me the content of every column concentrated in one field (example 2).
Why is this happenning? Why using the method in the docs does not iterate through all rows nicely? How would be the solution for example 1 but for all rows?
My code:
import csv
import pandas
import bibtexparser
import codecs
colnames = ['AUTORES', 'TITULO', 'OUTROS', 'DATA','NOMEREVISTA','LOCAL','VOL','NUM','PAG','PAG2','ISBN','ISSN','ISSN2','ERC','IF','DOI','CODEN','WOS','SCOPUS','URL','CODIGO BIBLIOGRAFICO','INDEXAÇÕES',
'EXTRAINFO','TESTE']
data = pandas.read_csv('test1.csv', names=colnames, delimiter =r";", encoding='latin1')#, nrows=1
df = pandas.DataFrame(data=data)
with codecs.open('test1.txt', 'w', encoding='latin1') as fh:
fh.write('#Book{Arp, ')
fh.write('\n')
rl = data.iterrows()
for i in rl:
ix = str(i)
fh.write(' Title = {')
fh.write(ix)
fh.write('}')
fh.write('\n')
PS: I'm new to python and programming, I know this code has flaws and it's not the most effective way to convert csv to bib.
The example row = next(df.iterrows())[1] intentionally only returns the first row.
df.iterrows() returns a generator over tuples describing the rows. The tuple's first entry contains the row index and the second entry is a pandas series with your data of the row.
Hence, next(df.iterrows()) returns the next entry of the generator. If next has not been called before, this is the very first tuple.
Accordingly, next(df.iterrows())[1] returns the first row (i.e. the second tuple entry) as a pandas series.
What you are looking for is probably something like this:
for row_index, row in df.iterrows():
convert_to_bib(row)
Secondly, all your writing to your file handle fh must happen within the block with codecs.open('test1.txt', 'w', encoding='latin1') as fh:
because at the end of the block the file handle will be closed.
For example:
with codecs.open('test1.txt', 'w', encoding='latin1') as fh:
# iterate through all rows
for row_index, row in df.iterrows():
# iterate through all elements in the row
for colname in df.columns:
row_element = row[colname]
fh.write('%s = {%s},\n' % (colname, str(row_element)))
Still I am not sure if the names of the columns exactly match the bibtex fields you have in mind. Probably you have to convert these first. But I hope you get the principle behind the iterations :-)
Python 2.6(necessary for the job)
import csv
list = ['apple,whiskey,turtle', 'orange,gin,wolf', 'banana,vodka,sparrow']
fieldNames = ['Fruit', 'Spirit', 'Animal']
reader = csv.DictReader(list,fieldnames= fieldNames)
for row in reader:
print row['Fruit']
for row in reader:
print row['Fruit']
I have some code that generates a uniform list of items per row, making a list object. For ease of use I used the csv module's DictReader to step through the rows and do any calculations I need to but when I try to iterate a second time, I get no output. I suspect the end of the list is being treated like an EOF but I am unable to 'seek' to the beginning of the list to do the iteration again.
Any suggestions on what I can do? Perhaps there is a better way than using the CSV, it just seemed really convenient.
New Code
import csv
list = ['apple,"whiskey,rum",turtle', 'orange,gin,wolf', 'banana,vodka,sparrow']
processed = []
fieldNames = ['Fruit', 'Spirit', 'Animal']
reader = csv.DictReader(list,fieldnames= fieldNames, quoatechar = '"')
for row in reader:
processed.append(row)
print row
for row in processed:
print row['Fruit']
for row in processed:
print row['Spirit']
#jonrsharpe suggested placing the rows of reader into a list. It works perfectly for what I had in mind. Thank you everyone.
You're indeed correct that iterating over the rows once is what the DictReader provides. So your options are:
Create a new DictReader and iterate again (seems wasteful)
Iterate over the rows once and perform all computations that you want to perform
Iterate over the rows once, store the data in another data structure and iterate over that data structure as many times as you wish.
Also, if you have only the list and the field names you don't need a DictReader to do the same thing. If you know the data is relatively straightforward (no comma's inside the data for example and all the same number of items) then you can simply do:
merged = [zip(fieldnames, row.split(",")) for row in my_list]
print merged