473,382 Members | 1,692 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,382 software developers and data experts.

to write set of values to a file from python

hi everybody

i want to write a set of values to a file from python.
For ex:: the fields name will "comp name", "ip addr", "mac addr" etc.
And below all these fields i ll have the values for these fields.

it should look some what like this.

comp name ipaddr macaddr

jdasfhjashd 234.347.23.12
334.12.354.43.232
dfdsfusdaufisa 234.533.45.12 89.234.234.2343
sfdidsfoui 234.45.23.56
89.343.23.45.233

something like thiss.

so which is the best way to do this.
I mean which file format would be the best to choose , to dump all
these values from my python script.

Will it be a ".ini" file format? or ".xls" or ".txt" which will be the
better one.
so that later it will be easy for me to read this file.

thanks in advance for the help

regards
yogi

Dec 14 '05 #1
11 9341
mu*******@yahoo.com schrieb:
hi everybody

i want to write a set of values to a file from python.
For ex:: the fields name will "comp name", "ip addr", "mac addr" etc.
And below all these fields i ll have the values for these fields.

it should look some what like this.

comp name ipaddr macaddr

jdasfhjashd 234.347.23.12
334.12.354.43.232
dfdsfusdaufisa 234.533.45.12 89.234.234.2343
sfdidsfoui 234.45.23.56
89.343.23.45.233

something like thiss.

so which is the best way to do this.
I mean which file format would be the best to choose , to dump all
these values from my python script.

Will it be a ".ini" file format? or ".xls" or ".txt" which will be the
better one.
so that later it will be easy for me to read this file.

thanks in advance for the help

regards
yogi

I would use a comma separated values (CSV) file.
Have a look at the csv module
<http://www.python.org/doc/2.4.2/lib/module-csv.html>.

Bye,
Dennis
Dec 14 '05 #2
hi dennis,
thanks for the help, itseems its good way to go.
i tried it, and i liked the idea, but there is one problem with it.

its printing each character in a seperate row where as
i want each string in a seperate column?

so how can i do that?? Any help for this.

thanks and regards
yogi

Dec 14 '05 #3
mu*******@yahoo.com schrieb:
[...]
its printing each character in a seperate row where as
i want each string in a seperate column?

so how can i do that?? Any help for this.
[...]


Could you post your code here? Or explain what you did exactly.

Bye,
Dennis
Dec 14 '05 #4
I have tried with the following code

import csv
file = open("some.csv","wb")
writer = csv.writer(file)
list = ["CompName", "IpAddr", "MacAddr","OpSys"]
for row in list:
writer.writerow(row)

file.close()

And the result am getting in a "some.csv" file is as below

c o m p N a m e
I p A d d r
M a c A d d r
O p S y s

each charatecr its printing in a different cell of excel sheet(some.csv
file).
so can i print the whole strings like "compName" "ipAddr" etc in a
different cells(columns)

thanks and regards
yogi

Dec 14 '05 #5
Il 2005-12-14, mu*******@yahoo.com <mu*******@yahoo.com> ha scritto:
I have tried with the following code

import csv
file = open("some.csv","wb")
writer = csv.writer(file)
list = ["CompName", "IpAddr", "MacAddr","OpSys"]
for row in list:
writer.writerow(row)

file.close()


writerow() wants a sequence, a string is a sequence of chars and hence
it writes a char at time, replace with

writer.writerow([row])

--
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"
Dec 14 '05 #6
thanks lawrence
it did work.
and i have one more question for you

its printing the feilds name in the following way

CompName
IpAddr
MacAddr

that means each row its printing one field name, can i make it to print
each one of the field in different columns, in this way

CompName IpAddr MacAddr

and then to fill up the values for these fields , something like this
CompName IpAddr MacAddr
XXX 192.178.23.11 78.23.34.23.12
YYY 192.189.22.11 89.23.43.12.34
ZZZ 192.179.24.45 89.23.34.12.45

etc.

thanks again
yogi
Lawrence Oluyede wrote:
Il 2005-12-14, mu*******@yahoo.com <mu*******@yahoo.com> ha scritto:
I have tried with the following code

import csv
file = open("some.csv","wb")
writer = csv.writer(file)
list = ["CompName", "IpAddr", "MacAddr","OpSys"]
for row in list:
writer.writerow(row)

file.close()


writerow() wants a sequence, a string is a sequence of chars and hence
it writes a char at time, replace with

writer.writerow([row])

--
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"


Dec 14 '05 #7
On 14 Dec 2005 15:39:02 -0800, mu*******@yahoo.com wrote:
thanks lawrence
it did work.
and i have one more question for you

its printing the feilds name in the following way

CompName
IpAddr
MacAddr

that means each row its printing one field name, can i make it to print
each one of the field in different columns, in this way

CompName IpAddr MacAddr

and then to fill up the values for these fields , something like this
CompName IpAddr MacAddr
XXX 192.178.23.11 78.23.34.23.12
YYY 192.189.22.11 89.23.43.12.34
ZZZ 192.179.24.45 89.23.34.12.45

etc.


Ok, we'll copy your data:
data = """\ ... CompName IpAddr MacAddr
... XXX 192.178.23.11 78.23.34.23.12
... YYY 192.189.22.11 89.23.43.12.34
... ZZZ 192.179.24.45 89.23.34.12.45
... """

and define a generator that will deliver the test data above as a rows in the form
of lists of items, to simulate your source of rows:
def rowsource(): ... for line in data.splitlines():
... yield line.split()
...

See if that worked: for row in rowsource(): print row ...
['CompName', 'IpAddr', 'MacAddr']
['XXX', '192.178.23.11', '78.23.34.23.12']
['YYY', '192.189.22.11', '89.23.43.12.34']
['ZZZ', '192.179.24.45', '89.23.34.12.45']

Use csv with default options, which will separate with commas.
Make a writer that will output back to the screen instead of a file,
so we can see without having to mess with an actual file: import csv
import sys
csv_writer = csv.writer(sys.stdout) # or supply file open for writing
Write the same rows-as-item-lists as above:
for row in rowsource(): csv_writer.writerow(row) ...
CompName,IpAddr,MacAddr
XXX,192.178.23.11,78.23.34.23.12
YYY,192.189.22.11,89.23.43.12.34
ZZZ,192.179.24.45,89.23.34.12.45

Looks like nothing needed quoting, just comma separation.
Try something different:
csv_writer.writerow(['has space', 2.5, "has,comma", 'extra','fields','...']) has space,2.5,"has,comma",extra,fields,...

Only the comma needed special treatment.
csv_writer.writerow(['empties:', None, '',[], (), {}, False]) empties:,,,[],(),{},False

Looks like None and '' translate to the same empty fields (nothing between delimiting commas)
but the other stuff is getting converted by str or repr (we'll check which below)
csv_writer.writerow(['empties:', None, '','(one comma for each separated field)']) empties:,,,(one comma for each separated field)
csv_writer.writerow([.1]) 0.1 .1

0.10000000000000001

Apparently it's str, not repr being used, so you may want to convert to string representation
yourself, according to need. See also help(csv) for other options.

HTH

Regards,
Bengt Richter
Dec 15 '05 #8
hi
thanks every body for the help.

Now how can check whtr the row am reading is the last row or not??

for example for this below data in csv file

CompName,IpAddr,MacAddr
XXX,192.178.23.11,78.23.34.23.12
YYY,192.189.22.11,89.23.43.12.34
ZZZ,192.179.24.45,89.23.34.12.45

file = open ('C:\some.csv','r')
reader = csv.reader(file)
for row in reader:
print row
HERE HOW CAN I CHECK WHTR THIS ROW IS THE LAST ONE IN THE FILE

so that if at all i dint find what am searching for i can write that
information at the last row, after opening the file in a "append" mode.

thanks again for help

regards
yogi

Dec 15 '05 #9
mu*******@yahoo.com wrote:
hi
thanks every body for the help.

Now how can check whtr the row am reading is the last row or not??

for example for this below data in csv file

CompName,IpAddr,MacAddr
XXX,192.178.23.11,78.23.34.23.12
YYY,192.189.22.11,89.23.43.12.34
ZZZ,192.179.24.45,89.23.34.12.45

file = open ('C:\some.csv','r')
reader = csv.reader(file)
for row in reader:
print row
HERE HOW CAN I CHECK WHTR THIS ROW IS THE LAST ONE IN THE FILE
Don't do that!
so that if at all i dint find what am searching for i can write that
information at the last row, after opening the file in a "append" mode.

What you should do is use the "else" clause on the for statement, which
is only executed if the loop terminates normally; something like:

for row in reader:
if row is the one you want:
break
else:
add new row

Of course, this presumes you don;t want to just print out everything
that's in the file.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Dec 16 '05 #10
mu*******@yahoo.com wrote:
hi
thanks every body for the help.
Now how can check whtr the row am reading is the last row or not??

for example: ...
reader = csv.reader(file)
for row in reader:
print row
HERE HOW CAN I CHECK WHTR THIS ROW IS THE LAST ONE IN THE FILE

so that if at all i dint find what am searching for i can write that
information at the last row, after opening the file in a "append" mode.


What Steve Holden says is right. If it turns out you need to know
ahead of time, use a lagged input to determine whether it is last:

def lagged(source):
'''produce element,islast for elements in source'''
generator = iter(source)
previous = generator.next()
for element in generator:
yield previous, False
yield previous, True

file = open ('C:\some.csv','r')
reader = csv.reader(file)
for row, final in lagged(reader):
print row
if final:
print 'final:', row
else:
print 'leads:', row
--Scott David Daniels
sc***********@acm.org
Dec 16 '05 #11
Scott David Daniels wrote:

def lagged(source):
'''produce element,islast for elements in source'''
generator = iter(source)
previous = generator.next()
for element in generator:
yield previous, False
yield previous, True
Oops:
def lagged(source):
'''produce element,islast for elements in source'''
generator = iter(source)
previous = generator.next()
for element in generator:
yield previous, False
previous = element
yield previous, True

file = open ('C:\some.csv','r')
reader = csv.reader(file)
for row, final in lagged(reader):
print row
if final:
print 'final:', row
else:
print 'leads:', row
--Scott David Daniels
sc***********@acm.org

--
-Scott David Daniels
sc***********@acm.org
Dec 16 '05 #12

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

Similar topics

33
by: Nick Evans | last post by:
Hello there, I have been on and off learning to code (with python being the second language I have worked on after a bit of BASIC). What I really want to know is, if you are going to actually...
14
by: Xah Lee | last post by:
is there a way to condense the following loop into one line? # -*- coding: utf-8 -*- # python import re, os.path imgPaths= # change the image path to the full sized image, if it exists
18
by: jas | last post by:
Hi, I would like to start a new process and be able to read/write from/to it. I have tried things like... import subprocess as sp p = sp.Popen("cmd.exe", stdout=sp.PIPE)...
27
by: Ben Finney | last post by:
Antoon Pardon wrote: > I just downloaded your enum module for python > and played a bit with it. IMO some of the behaviour makes it less > usefull. Feedback is appreciated. I'm hoping to...
16
by: Preben Randhol | last post by:
Hi A short newbie question. I would like to extract some values from a given text file directly into python variables. Can this be done simply by either standard library or other libraries? Some...
10
by: Pierre Thibault | last post by:
Hello! I am currently trying to port a C++ code to python, and I think I am stuck because of the very different behavior of STL iterators vs python iterators. What I need to do is a simple...
7
by: jld730 | last post by:
In the example below, how would you write the in-memory xmldoc to a text file? In my real situation, I send a string to a web service (code 2 below) which returns XML/KML that I want to save to a...
3
by: dmitrey | last post by:
hi all, what's the best way to write Python dictionary to a file? (and then read) There could be unicode field names and values encountered. Thank you in advance, D.
4
by: McA | last post by:
Hi all, probably a dumb question, but I didn't find something elegant for my problem so far. In perl you can unpack the element of a list to variables similar as in python (a, b, c = ), but...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: 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...

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.