473,386 Members | 1,786 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Python CSV writer confusion.

Hi. I am trying to write out a csv file with | instead of comma,
because I have a field that may have many commas in it. I read in a
csv file, sort it, and want to write it out again.

I read the example that says:

import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerows(someiterable)

The "someiterable" is what is confusing me.

class Image(object):
def __init__(self, title, date, genre, data, value, filename):
params = locals()
del params['self']
self.__dict__.update(params)
def __repr__(self):
all_items = self.__dict__.items()
return '%s,%s,%s,%s,%s, %s' % (self.title, self.date,
self.genre, self.data, self.value, self.filename)

def read_images(filename):
csv_file = open(filename, "rb")
reader = csv.reader(csv_file, dialect='excel', delimiter='|')
images = [Image(*[field.strip() for field in row]) for row in
reader]
csv_file.close()
return books

def sort_images(filename, *attr_names):
csv_file = open(filename, "rb")
reader = csv.reader(csv_file, dialect='excel', delimiter='|')
if __name__ == '__main__':
images = read_images(r"D:\path\to\imagespipe.csv")

def get_key(*attr_names):
def key(image):
return [getattr(image, name) for name in attr_names]
return key

images.sort(key = get_key("filename"))

t = open(r'D:\path\to\filename_sort1.csv', 'w')

for image in images:
print book
#t.write('%s\n' % book) %Before I needed | delimited, this
worked
#csv.writer(t, dialect='excel', delimiter='|')
output = csv.writer(t, dialect='excel', delimiter='|')
output.writerows()
#output.writerows(image)
#output.writerow(image)

t.close()

This returns an error that says "Error: sequence expected"

My understanding of this is that I am creating a list of lists and I am
iterating over it (for image in images), and that image is a list, and
is therefore iterable...?

I am a bit new at this, and would greatly appreciate any assistance.

TIA

googleboy

Sep 15 '05 #1
2 13876
The someiterable should be something that has a .next
method. That would be a list or any object with such a
method. In your case it would be the images list.
The writer method will iterate over the list and write
everything out for you. Don't put it inside a loop
yourself. More like (not tested):

import csv
..
..
..
outfile=open(r'D:\path\to\filename_sort1.csv', 'w')
CSVwriter=csv.writer(outfile, dialect='excel', delimiter='|')
CSVwriter.writerows(images)
Larry Bates


if __name__ == '__main__':
images = read_images(r"D:\path\to\imagespipe.csv")

def get_key(*attr_names):
def key(image):
return [getattr(image, name) for name in attr_names]
return key

images.sort(key = get_key("filename"))

t = open(r'D:\path\to\filename_sort1.csv', 'w')

for image in images:
print book
#t.write('%s\n' % book) %Before I needed | delimited, this
worked
#csv.writer(t, dialect='excel', delimiter='|')
output = csv.writer(t, dialect='excel', delimiter='|')
output.writerows()
#output.writerows(image)
#output.writerow(image)

t.close()

-Larry Bates
googleboy wrote: Hi. I am trying to write out a csv file with | instead of comma,
because I have a field that may have many commas in it. I read in a
csv file, sort it, and want to write it out again.

I read the example that says:

import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerows(someiterable)

The "someiterable" is what is confusing me.

class Image(object):
def __init__(self, title, date, genre, data, value, filename):
params = locals()
del params['self']
self.__dict__.update(params)
def __repr__(self):
all_items = self.__dict__.items()
return '%s,%s,%s,%s,%s, %s' % (self.title, self.date,
self.genre, self.data, self.value, self.filename)

def read_images(filename):
csv_file = open(filename, "rb")
reader = csv.reader(csv_file, dialect='excel', delimiter='|')
images = [Image(*[field.strip() for field in row]) for row in
reader]
csv_file.close()
return books

def sort_images(filename, *attr_names):
csv_file = open(filename, "rb")
reader = csv.reader(csv_file, dialect='excel', delimiter='|')
if __name__ == '__main__':
images = read_images(r"D:\path\to\imagespipe.csv")

def get_key(*attr_names):
def key(image):
return [getattr(image, name) for name in attr_names]
return key

images.sort(key = get_key("filename"))

t = open(r'D:\path\to\filename_sort1.csv', 'w')

for image in images:
print book
#t.write('%s\n' % book) %Before I needed | delimited, this
worked
#csv.writer(t, dialect='excel', delimiter='|')
output = csv.writer(t, dialect='excel', delimiter='|')
output.writerows()
#output.writerows(image)
#output.writerow(image)

t.close()

This returns an error that says "Error: sequence expected"

My understanding of this is that I am creating a list of lists and I am
iterating over it (for image in images), and that image is a list, and
is therefore iterable...?

I am a bit new at this, and would greatly appreciate any assistance.

TIA

googleboy

Sep 15 '05 #2
googleboy <my******@yahoo.com> wrote:
Hi. I am trying to write out a csv file with | instead of comma,
because I have a field that may have many commas in it. I read in a
csv file, sort it, and want to write it out again.


CSV can handle comma within the field.

--
William Park <op**********@yahoo.ca>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
http://home.eol.ca/~parkw/thinflash.html
BashDiff: Super Bash shell
http://freshmeat.net/projects/bashdiff/
Sep 16 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

699
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro...
3
by: srijit | last post by:
Hello, Here is an example code of xml writer in Python+PythonNet, Ironpython and Boo. The codes look very similar. Regards, Srijit Python + PythonNet: import CLR
75
by: Xah Lee | last post by:
http://python.org/doc/2.4.1/lib/module-re.html http://python.org/doc/2.4.1/lib/node114.html --------- QUOTE The module defines several functions, constants, and an exception. Some of the...
5
by: Michael Sperlle | last post by:
Is it possible? Bestcrypt can supposedly be set up on linux, but it seems to need changes to the kernel before it can be installed, and I have no intention of going through whatever hell that would...
5
by: Cameron Laird | last post by:
Question: import subprocess, StringIO input = StringIO.StringIO("abcdefgh\nabc\n") # I don't know of a compact, evocative, and # cross-platform way to exhibit this behavior. # For now, depend...
19
by: Chris Brat | last post by:
I've seen a few posts, columns and articles which state that one of the advantages of Python is that code can be developed x times faster than languages such as <<Insert popular language name...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.