It's been a year or so since I written Python code, so maybe
I am just doing something really dumb, but...
Documentation
=============
class DictReader(csvfile[,fieldnames=None,
[,restkey=None[, restval=None[, dialect='excel'
[, *args, **kwds]]]]])
Create an object which operates like a regular reader
but maps the information read into a dict whose keys
are given by the optional fieldnames parameter. If the
fieldnames parameter is omitted, the values in the
first row of the csvfile will be used as the fieldnames.
Code
====
import csv
r = csv.DictReader('C:\Temp\Book1.csv')
print r.next()
# EOF
Output
======
{'C': ':'} 10 2301
Jeff Blaine wrote:
It's been a year or so since I written Python code, so maybe
I am just doing something really dumb, but...
Documentation
=============
class DictReader(csvfile[,fieldnames=None,
[,restkey=None[, restval=None[, dialect='excel'
[, *args, **kwds]]]]])
Create an object which operates like a regular reader
but maps the information read into a dict whose keys
are given by the optional fieldnames parameter. If the
fieldnames parameter is omitted, the values in the
first row of the csvfile will be used as the fieldnames.
Code
====
import csv
r = csv.DictReader('C:\Temp\Book1.csv')
print r.next()
# EOF
here's the documentation for the regular reader, from Python 2.5:
reader(...)
csv_reader = reader(iterable [, dialect='excel']
[optional keyword args])
for row in csv_reader:
process(row)
The "iterable" argument can be any object that returns a line
of input for each iteration, such as a file object or a list.
...
so the reader is simply looping over the characters in your filename. try
r = csv.DictReader(open('C:\Temp\Book1.csv'))
instead.
</F>
I see what's wrong. Me. Wow am I ever rusty.
Jeff Blaine wrote:
It's been a year or so since I written Python code, so maybe
I am just doing something really dumb, but...
Documentation
=============
class DictReader(csvfile[,fieldnames=None,
[,restkey=None[, restval=None[, dialect='excel'
[, *args, **kwds]]]]])
Create an object which operates like a regular reader
but maps the information read into a dict whose keys
are given by the optional fieldnames parameter. If the
fieldnames parameter is omitted, the values in the
first row of the csvfile will be used as the fieldnames.
Code
====
import csv
r = csv.DictReader('C:\Temp\Book1.csv')
print r.next()
# EOF
Output
======
{'C': ':'}
Jeff Blaine wrote:
It's been a year or so since I written Python code, so maybe
I am just doing something really dumb, but...
Documentation
=============
class DictReader(csvfile[,fieldnames=None,
[,restkey=None[, restval=None[, dialect='excel'
[, *args, **kwds]]]]])
Create an object which operates like a regular reader
but maps the information read into a dict whose keys
are given by the optional fieldnames parameter. If the
fieldnames parameter is omitted, the values in the
first row of the csvfile will be used as the fieldnames.
Code
====
import csv
r = csv.DictReader('C:\Temp\Book1.csv')
Problem 1:
"""csvfile can be any object which supports the iterator protocol and
returns a string each time its next method is called -- file objects
and list objects are both suitable. If csvfile is a file object, it
must be opened with the 'b' flag on platforms where that makes a
difference."""
So, open the file, so that the next() method returns the next chunk of
content, not the next byte in the name of the file.
Note that the arg is called "csvfile", not "csvfilename".
Problem 2: [OK in this instance, but that's like saying you have taken
one step in a minefield and are still alive] backslashes and Windows
file names:
If you were to write 'c:\temp\book1.csv', it would blow up ... because
\t -tab and \b -backspace. Get into the habit of *always* using raw
strings r'C:\Temp\Book1.csv' for Windows file names (and re patterns).
You could use double backslashing 'C:\\Temp\\Book1.csv' but it's
uglier.
print r.next()
# EOF
Output
======
{'C': ':'}
HTH,
John
John Machin wrote:
If you were to write 'c:\temp\book1.csv', it would blow up ... because
\t -tab and \b -backspace. Get into the habit of *always* using raw
strings r'C:\Temp\Book1.csv' for Windows file names (and re patterns).
You could use double backslashing 'C:\\Temp\\Book1.csv' but it's
uglier.
....alternatively you can just use 'unix slashes', e.g.
'c:/temp/book1.csv', since those work just fine 'cause the Windows
APIs deal with them properly.
-tom!
Tom Plunket wrote:
John Machin wrote:
If you were to write 'c:\temp\book1.csv', it would blow up ... because
\t -tab and \b -backspace. Get into the habit of *always* using raw
strings r'C:\Temp\Book1.csv' for Windows file names (and re patterns).
You could use double backslashing 'C:\\Temp\\Book1.csv' but it's
uglier.
...alternatively you can just use 'unix slashes', e.g.
'c:/temp/book1.csv', since those work just fine 'cause the Windows
APIs deal with them properly.
Not all APIs do the right thing. If you fire up the cmd.exe shell and
feed it slashes as path separators, it barfs. Example:
C:\junk>dir c:/junk/*.bar
Invalid switch - "junk".
Hence the advice to use rawstrings with backslashes -- they work under
all circumstances.
>...alternatively you can just use 'unix slashes', e.g. 'c:/temp/book1.csv', since those work just fine 'cause the Windows APIs deal with them properly.
JohnNot all APIs do the right thing. If you fire up the cmd.exe shell
Johnand feed it slashes as path separators, it barfs. Example:
John C:\junk>dir c:/junk/*.bar
John Invalid switch - "junk".
JohnHence the advice to use rawstrings with backslashes -- they work
Johnunder all circumstances.
I think he means "the Windows APIs" within a Python program.
Skip
John Machin wrote:
Tom Plunket wrote:
>>John Machin wrote:
>>>If you were to write 'c:\temp\book1.csv', it would blow up ... because \t -tab and \b -backspace. Get into the habit of *always* using raw strings r'C:\Temp\Book1.csv' for Windows file names (and re patterns). You could use double backslashing 'C:\\Temp\\Book1.csv' but it's uglier.
...alternatively you can just use 'unix slashes', e.g. 'c:/temp/book1.csv', since those work just fine 'cause the Windows APIs deal with them properly.
Not all APIs do the right thing. If you fire up the cmd.exe shell and
feed it slashes as path separators, it barfs. Example:
C:\junk>dir c:/junk/*.bar
Invalid switch - "junk".
Hence the advice to use rawstrings with backslashes -- they work under
all circumstances.
The command shell is not an API.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
On 2/11/2006 2:38 PM, sk**@pobox.com wrote:
>...alternatively you can just use 'unix slashes', e.g.
>'c:/temp/book1.csv', since those work just fine 'cause the Windows
>APIs deal with them properly.
JohnNot all APIs do the right thing. If you fire up the cmd.exe shell
Johnand feed it slashes as path separators, it barfs. Example:
John C:\junk>dir c:/junk/*.bar
John Invalid switch - "junk".
JohnHence the advice to use rawstrings with backslashes -- they work
Johnunder all circumstances.
I think he means "the Windows APIs" within a Python program.
Skip
I too think he meant that. I left the mental gymnastics of wrapping what
I wrote into an os.system call as an exercise for the reader.
| >>import os
| >>os.system("dir c:/junk/*.bar")
| Invalid switch - "junk".
| 1
| >>os.system(r"dir c:\junk\*.bar")
| [snip]
| 02/11/2006 01:21 PM 8 foo.bar
| [snip]
| 0
| >>>
Cheers,
John
John Machin wrote:
Not all APIs do the right thing. If you fire up the cmd.exe shell and
feed it slashes as path separators, it barfs. Example:
C:\junk>dir c:/junk/*.bar
Invalid switch - "junk".
Hence the advice to use rawstrings with backslashes -- they work under
all circumstances.
we went through this a couple of days ago; all Windows API:s are
*documented* to accept backward or forward slashes, the command shell is
*documented* to only accept backward slashes.
if you're wrapping some cmd.exe command in an internal API, it's usually
easier to call "os.path.normpath" the last thing you do before you call
"os.system", than to get all the backslashes right in your code.
also see: http://www.effbot.org/pyfaq/why-can-...-backslash.htm
</F>
Fredrik Lundh wrote:
if you're wrapping some cmd.exe command in an internal API, it's usually
easier to call "os.path.normpath" the last thing you do before you call
"os.system", than to get all the backslashes right in your code.
also see:
http://www.effbot.org/pyfaq/why-can-...-backslash.htm
and as just I pointed out in a comment on that page, getting the slashes
right doesn't help you with spaces in filenames. to write reliable code
for os.system, you want something like:
import os.path
import subprocess
def mysystem(command, *files):
files = map(os.path.normpath, files)
files = subprocess.list2cmdline(files)
return os.system(command + " " + files)
mysystem("more", "/program files/subversion/readme.txt")
but then you might as well use subprocess.call, of course.
</F> This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Bernard Delmée |
last post by:
Hello, I can't seem to be able to specify the delimiter when building a
DictReader()
I can do:
inf = file('data.csv')
rd = csv.reader( inf, delimiter=';' )
for row in rd:
# ...
|
by: Irmen de Jong |
last post by:
Hello
I've got a nuisance with the cgi module. (Python 2.3.2)
When processing a HTTP POST request, it ignores the
query string parameters that may also be present.
I.e. only the parameters from...
|
by: Thomas Aanensen |
last post by:
How can I get the names of the classes in a specific module? (I don't need
the subclasses or superclasses)
Thomas
|
by: Ramon Felciano |
last post by:
Hi --
I'm using the csv module to parse a tab-delimited file and wondered
whether there was a more elegant way to skip an possible header line.
I'm doing
line = 0
reader =...
|
by: Michael Hoffman |
last post by:
Many of you are familiar with Jason Orendorff's path module
<http://www.jorendorff.com/articles/python/path/>, which is frequently
recommended here on c.l.p. I submitted an RFE to add it to the...
| |
by: David Pratt |
last post by:
Hi. I have had good success with CSV module but recently came across
problem with reading excel from Mac Office. The trouble is with line
endings. Instead of \r\n you have just \r and the file as...
|
by: Andrew McLean |
last post by:
I have a bunch of csv files that have the following characteristics:
- field delimiter is a comma
- all fields quoted with double quotes
- lines terminated by a *space* followed by a newline
...
|
by: brnstrmrs |
last post by:
I am trying to use the dictionary reader to import the data from a csv
file and create a dictnary from it but just can't seem to figure it
out.
Here is my code:
my csv files looks like this:...
|
by: =?ISO-8859-1?Q?S=E9bastien_Sabl=E9?= |
last post by:
WHAT IS IT:
The Sybase module provides a Python interface to the Sybase relational
database system. It supports all of the Python Database API, version
2.0 with extensions.
The module is...
|
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,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...
| | |