The concept is mostly fine. You either assume that all cells in the
changed row are to be text cells or omit details of how you would ensure
that a line containing '123.45' would be written to the output worksheet
as a number cell.
However the execution is not mostly fine. In particular:
(1) apart from x and y, the names used make it look like a deliberate
obfuscation exercise
(2) there's a syntax error
(3) there are three logic errors
If you have any questions about the detailed critique and rewrite below,
please don't hesitate to ask.
HTH,
John
8<---
# Dramatis personae, in order of first appearance:
# EDIT function
# n xlrd.Book instance
# bk xlrd.Sheet instance #ARGH
# f file instance IMMEDIATELY RE-USED as list of strings # AARRGGHH
# m xlwt.Workbook instance
# <anon.> xlwt.Worksheet instance # AAARRRGGGHHH
# y int, used as row index
# x int, used as column index
def EDIT(n):
bk = n.sheet_by_index(0)
f = open('DATAFILE','r')
f = f.readlines()
m = xlwt.Workbook()
m.add_sheet('1')
for y in range(len(bk.col(0))): #### use the worksheet's nrows
attribute!
if(y == f[0]): #### will fail; 123 != "123\n"
# for x in range(1:len(f)-1): #### syntax error
# for x in range(1, len(f)-1): #### logic errors
# m.get_sheet(0).write(y,x,f[x])
# The above code writes data starting on column B and omits
last item
for x in range(1, len(f)):
m.get_sheet(0).write(y, x - 1, f[x])
else:
for x in range(len(bk.row(y))):
m.get_sheet(0).write(y,x,bk.row(y)[x].value)
# [untested]
def edit_workbook(rd_book, datafile_path, new_workbook_path):
rd_sheet = rd_book.sheet_by_index(0)
f = open(datafilename,'r')
target_rowx = int(f.readline())
assert 0 <= target_rowx < rd_sheet.nrows
replacement_values = [line.rstrip() for line in f]
# Purpose of using rstrip is to remove '\n'
# (and any other trailing whitespace)
f.close()
wt_book = xlwt.Workbook()
wt_sheet = wt_book.add_sheet(rd_sheet.name)
for rowx in range(rd_sheet.nrows):
if rowx == target_rowx:
source = replacement_values
else:
source = rd_sheet.row_values(rowx)
for colx, value in enumerate(source):
wt_sheet.write(rowx, colx, value)
wt_book.save(new_workbook_path)
8<---
xlutils.copy will likely help you a lot, when it arrives.
However, for inserting rows, you likely want xlutils.filter, which is
here already...
> and thank you for your help. Do you think it would be easier to just
> run copy the xlrd workbook
> to the xlwt workbook instnaces? and them modify the xlwt before
> saving?
That's exactly what xlutils.copy will do in one function call...
> or would u suggest I learn COM and use that? Is the xlrd easy
> compatable with COM?
Apples and oranges, they can both work with .xls data, but not at the
same time ;-)
cheers,
Chris
--
Simplistix - Content Management, Zope & Python Consulting
- http://www.simplistix.co.uk
New topic, new subject, OK?
> ok so sometimes when i try to do xlwt.write(....) it will give me this
> error
>
> IOError: [Errno 22] invalid mode ('wb') or filename: 'FILE.xls'
That would be quite astonishing. There is no write function exposed at
the top level of the package. Output is done only in response to a
Workbook.save_as(file_path) call.
>
> i understand the error well enough, but it shows up at inconsistent
> times. Sometimes if I alter the path to be
>
> 'C:\......\FILE.xls'
>
> it works, but not always, is there some specific way i should set the
> save path? all i want it to do is save it over the origninal, and
> workbook.name doesnt exist as far i know
What is "workbook.name"?
So that we can help you, you will have to divulge information like:
1. Windows: what version, what service pack
2. Python: what version
3. xlwt: the released version? If not, what svn revision?
4. The full traceback that is printed when such a problem happens.
Copy/paste, *don't* retype anything. We need to see *exactly* what is
there; "FILE" is useless. Also we need to see exactly where in xlwt the
error is being raised.
5. Is the path that you are specifying on a network share, or anything
else that's not a normal plain vanilla path into which you can save
files? Assuming the problematic path is c:\foo\bar.xls, can you use
Notepad to save a file called c:\foo\bar.txt?
6. "Alter the path"?? Is the file path hardcoded in your script? Please
send me a copy of your script.
7. What is your locale? Are there any non-ASCII characters in the paths
that fail? Are there any invalid characters, like "?"?
*Some* of the questions. Notably you didn't answer the one about whether
you can use Notepad to save a .txt file in the same place.
> im using windows xp, I'm guessing the most up to date version (work
> computer)
Don't guess; it is pointless and irritates the [expletive deleted] out
of people who are trying to help you.
> python 2.6
2.6.0 or 2.6.1?
> xlwt release version
> the full trace back
> --------------------------------------------------------
> Traceback (most recent call last):
> File "C:\Python26\Lib\XLP3.py", line 397, in onEdit
> self.EDIT(file_name)
> File "C:\Python26\Lib\XLP3.py", line 377, in EDIT
> new_book.save(new_book_path.__str__())
Why do you have .__str__() there???
If you put this line in
print "waste of keystrokes:", new_book_path.__str__() == new_book_path
what is printed?
> File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 501, in
> save
> doc.save(filename, self.get_biff_data())
> File "C:\Python26\lib\site-packages\xlwt\CompoundDoc.py", line 507,
> in save
> f = open(file_name_or_filelike_obj, 'wb')
> IOError: [Errno 22] invalid mode ('wb') or filename: 'testy.xls'
> -----------------------------------------------------------
>
> the file it self is called "testy.xls" and its saved in the c: drive,
> the path for the file is
> C:\Python26\Lib\testy.xls
Unconfuse me: it's saved there as in "it already exists there", or as in
"there is an attempt to save it there but the attempt fails"?
It is possible that Python has been installed in such a fashion that you
don't have write access to C:\Python26\Lib. Who installed it and what
option was chosen: "everyone" or "myself"? Have you been able to create
any files at all in that folder?
Do you sometimes log on as an administrator and sometimes as an ordinary
user?
In any case, it is not a very good idea at all to be dumping your files
in such a folder. Set up a folder hierarchy for your projects somewhere
well away from installed software.
> this is the save script
> file_name = 'testy.xls'
> self.EDIT(file_name)
That isn't the whole script.
How do you know that C:\Python26\Lib\ is where the save attempt is being
made?
If you insert:
import os
print "current working directory is", repr(os.getcwd())
in front of the line
new_book.save(new_book_path.__str__())
what do you see printed?
Cheers,
John
>
> the current current working directory is 'C:\\Python26\\Lib'
>
> that is were the the attempt is being made because sometimes I can
> save it there, and other times I cant.
> its not always consistent.
With one particular new_book_path, e.g. testy.xls, does it always fail,
never fail, or sometimes fail?
If the story is that with one bunch of paths it always fails, and with
another bunch of paths it never fails, please tell us the two bunches.
Just as an experiment, please try these:
bunch (1) testy.xls, besty..., festy, mesty, nesty
bunch (2) cesty, desty, zesty
> if you want to see my whole EDIT method here you go
>
[snip]
insert here:
print "new_book_path", repr(new_book_path)
> new_book.save(new_book_path)
> the current 'new_book_path' is
>
> self.EDIT( 'testy.xls')
>
When a failure happens, e.g. with 'testy.xls', what happens when you try
this at the Python interactive prompt:
>>> import os; print os.getcwd() # should say 'C:\\Python26\\Lib'
>>> open('testy.xls', 'wb')
>>> open('c:\\Python26\\Lib\\testy.xls', 'wb')
>>> open('c:/Python26/Lib/testy.xls', 'wb')
>>> open(r'c:\Python26\Lib\testy.xls', 'wb')
>>> open('c:\Python26\Lib\testy.xls', 'wb')
Please answer the previously asked question: Is the outcome dependant on
whether you are logged on as an Administrator or not?
Please answer the question.
>>
>> If the story is that with one bunch of paths it always fails, and with
>> another bunch of paths it never fails, please tell us the two bunches.
>>
>> Just as an experiment, please try these:
>>
>> bunch (1) testy.xls, besty..., festy, mesty, nesty
>> bunch (2) cesty, desty, zesty
>
> i tried several different names and and the same result came up, works
> for a little while then
> i get the error
Do you mean that (for example) you tried testy.xls a few times and at
first it worked (how many times?) and then stopped working and you tried
cesty.xls a few times and at first it worked (how many times?) and
then stopped working?
If not (and perhaps even if so), could you please state what you did and
what the outcome was in a clear and unambiguous fashion e.g.
testy ok
testy ok
testy fail
cesty ok
cesty ok
cesty fail
That sounds like a good idea.
However the error that I would expect if a file with the same path is
open in Excel is *DIFFERENT* ...
IOError: [Errno 13] Permission denied: 'fubar.xls'