Re: [Tutor] create an xls file using data from a txt file
Steve Willoughby wrote: On 11-May-11 15:54, Prasad, Ramit wrote: Core windows commands don't generally accept it, including native Windows applications (although sometimes they're lenient in what they accept). It'll work for command-line Python script usage because it's *python* that allows them, not *windows*. They work in *Windows* command prompt natively. Respectfully, I think you aren't clear on how command line execution works. Hopefully I can help a little (yes, there are enough cases where it'll bite you that it's good to know this). Some apps do not work well that is true, but the reason that theywork like this with Python is NOT because Python allows it but because Windows does. I highly doubt Python checks for / and converts it to \\ (or does any complicated checking of file strings). YMMV for apps, but I have never had a problem with '/' on the command prompt. It is an important caveat to note that this behavior is not Guaranteed. Actually, yes, that's exactly what Python (or actually the underlying file handling libraries it's built with) is doing on Windows. There is a decades-long tradition of C compilers (et al) doing this conversion for the sake of all the ported Unix C programs that people wanted to run on Windows (or, at the time, MSDOS). If Windows natively supported it, then you could do this: C:\ DIR /users/fred/desktop C:\ DEL /temp/myfile Or try running your Python program like C:\ /python27/python.exe scriptname.py That doesn't work either, because Windows is NOT in any way at all interpreting the / characters. So why does this work: C:\ myscript.py /temp/myfile /users/fred/desktop or even C:\ \python27\python.exe myscript.py /temp/myfile That works because Windows hands ALL of the argument strings, as-is, with NO interpretation, to the application to deal with. In this case, the application is Python, and Python is going to the extra work to interpret the / characters as \ characters when you try to use them in open() calls and the like. The following suggests otherwise: Note File I/O functions in the Windows API convert / to \ as part of converting the name to an NT-style name, except when using the \\?\ prefix as detailed in the following sections. (Found at http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx ) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
To confirm: Python does *nothing* to convert automatically from one form of path separator to another. Windows from very early on, has accepted /-slashes as path separators to API calls. Where they don't work is: at the command shell itself presumably since slashes are commonly used to introduce options; and, sometimes, the Windows Shell API although I can't lay my hands on an example at the moment. If you were to write something in C to call CreateFile and pass a path such as c:/temp/temp.txt it would work without a problem because the Windows API accepts those kinds of paths. TJG ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
Respectfully, I think you aren't clear on how command line execution works. Hopefully I can help a little (yes, there are enough cases where it'll bite you that it's good to know this). True If Windows natively supported it, then you could do this: C:\ DIR /users/fred/desktop C:\ DEL /temp/myfile Or try running your Python program like C:\ /python27/python.exe scriptname.py That doesn't work either, because Windows is NOT in any way at all interpreting the / characters. C:\ /python27/python.exe scriptname.py Oh, really? Works for me. C:\/Python31/python.exe /temp/test.py File /temp/test.py, line 1 print 'Hello World' ^ SyntaxError: invalid syntax True that does not work for dir and del because both use '/' as the argument passing prefix, but that does not mean that Windows cannot handle it. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -Original Message- From: Steve Willoughby [mailto:st...@alchemy.com] Sent: Wednesday, May 11, 2011 6:24 PM To: Prasad, Ramit; tutor@python.org Subject: Re: [Tutor] create an xls file using data from a txt file On 11-May-11 15:54, Prasad, Ramit wrote: Core windows commands don't generally accept it, including native Windows applications (although sometimes they're lenient in what they accept). It'll work for command-line Python script usage because it's *python* that allows them, not *windows*. They work in *Windows* command prompt natively. Some apps do not work well that is true, but the reason that theywork like this with Python is NOT because Python allows it but because Windows does. I highly doubt Python checks for / and converts it to \\ (or does any complicated checking of file strings). YMMV for apps, but I have never had a problem with '/' on the command prompt. It is an important caveat to note that this behavior is not Guaranteed. Actually, yes, that's exactly what Python (or actually the underlying file handling libraries it's built with) is doing on Windows. There is a decades-long tradition of C compilers (et al) doing this conversion for the sake of all the ported Unix C programs that people wanted to run on Windows (or, at the time, MSDOS). If Windows natively supported it, then you could do this: C:\ DIR /users/fred/desktop C:\ DEL /temp/myfile Or try running your Python program like C:\ /python27/python.exe scriptname.py That doesn't work either, because Windows is NOT in any way at all interpreting the / characters. So why does this work: C:\ myscript.py /temp/myfile /users/fred/desktop or even C:\ \python27\python.exe myscript.py /temp/myfile That works because Windows hands ALL of the argument strings, as-is, with NO interpretation, to the application to deal with. In this case, the application is Python, and Python is going to the extra work to interpret the / characters as \ characters when you try to use them in open() calls and the like. -- Steve Willoughby / st...@alchemy.com A ship in harbor is safe, but that is not what ships are built for. PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
Maybe we're splitting hairs over semantics then. I thought there was confusion about what the CLI shell was doing with file separators as opposed to just handing the arguments as-is to the applications (which is true... the CLI doesn't really process them much, it's up to the application. Where in the application, though, this is dealt with is not where I think we disagree. In my original response, I clarified that, although as a short parenthetical note: On 12-May-11 02:25, Peter Otten wrote: Steve Willoughby wrote: Actually, yes, that's exactly what Python (or actually the underlying file handling libraries it's built with) is doing on Windows. There is the underlying file handling libraries would be the API calls. But that's not the CLI shell's doing. Although maybe that's what you meant all along. There are enough difference between the way the Windows CLI shell and Unix-derived command shells function in the handling of files and option handling that there's often confusion there which I thought was what was happening here too, that the OP was saying the CLI was somehow doing the translation. -- Steve Willoughby / st...@alchemy.com A ship in harbor is safe, but that is not what ships are built for. PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
On 01/-10/-28163 02:59 PM, tax botsis wrote: I have the following txt file that has 4 fields that are tab separated: the first is the id and the other three show the results per test. 152 TEST1 valid TEST3 good TEST2 bad 158 TEST2 bad TEST1 bad TEST4 valid . . . Based on the above txt I need to create an xls file having as headers ID, TEST1, TEST2, TEST3, TEST4 and the values valid, bad, etc under the corresponding column: ID TEST1 TEST2 TEST3 TEST4 152 valid bad good 158 bad bad valid I tried to work that out with xlwt but couldn't. Actually, I started working on the following script but I couldn't even split the line for further processing: import xlwt wbk = xlwt.Workbook() sheet = wbk.add_sheet('sheet 1') row = 0 f = open('C:/test.txt','r') for line in f: # separate fields by tab L = line.rstrip().split('\t') Looks to me like you've split a line just fine. This line needs to be indented, however, so that it's inside the for loop. What happens if you simply add a print L and temporarily comment out the rest of the code? Once you're confident about what's in L, how about if you figure out what data you could put into sheet.write() instead of printing it ? Hint: you probably want a for loop to process the list L. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
On 11 May 2011 03:57, tax botsis taxbot...@gmail.com wrote: I tried to work that out with xlwt but couldn't. Actually, I started working on the following script but I couldn't even split the line for further processing: OK, I've thrown together a quick sample demonstrating all the concepts you need (obviously you need to take from this what is relevant to you): import csv import xlwt import os import sys # Look for input file in same location as script file: inputfilename = os.path.join(os.path.dirname(sys.argv[0]), 'tabdelimited.txt') # Strip off the path basefilename = os.path.basename(inputfilename) # Strip off the extension basefilename_noext = os.path.splitext(basefilename)[0] # Get the path of the input file as the target output path targetoutputpath = os.path.dirname(inputfilename) # Generate the output filename outputfilename = os.path.join(targetoutputpath, basefilename_noext+'.xls') # Create a workbook object workbook = xlwt.Workbook() # Add a sheet object worksheet = workbook.add_sheet(basefilename_noext, cell_overwrite_ok=True) # Get a CSV reader object set up for reading the input file with tab delimiters datareader = csv.reader(open(inputfilename, 'rb'), delimiter='\t', quotechar='') # Process the file and output to Excel sheet for rowno, row in enumerate(datareader): for colno, colitem in enumerate(row): worksheet.write(rowno, colno, colitem) # Write the output file. workbook.save(outputfilename) # Open it via the operating system (will only work on Windows) # On Linux/Unix you would use subprocess.Popen(['xdg-open', filename]) os.startfile(outputfilename) The code is also available at the following URL in case the formatting gets eaten by the mail system: http://pastebin.com/APpM7EPf Regards Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
hi all, thanks for this sharing. when i copy and run this code, i got this error: Traceback (most recent call last): File C:/Python25/myscript/excel/sampleexcel.py, line 1, in module import csv File C:/Python25/myscript/excel\csv.py, line 3, in module w=csv.writer(open('output.csv','w')) AttributeError: 'module' object has no attribute 'writer' i'm using Python 2.5 and Win XP. pls help advise. thanks tcl Date: Wed, 11 May 2011 14:05:12 +0100 From: wpr...@gmail.com To: taxbot...@gmail.com CC: tutor@python.org Subject: Re: [Tutor] create an xls file using data from a txt file On 11 May 2011 03:57, tax botsis taxbot...@gmail.com wrote: I tried to work that out with xlwt but couldn't. Actually, I started working on the following script but I couldn't even split the line for further processing: OK, I've thrown together a quick sample demonstrating all the concepts you need (obviously you need to take from this what is relevant to you): import csv import xlwt import os import sys # Look for input file in same location as script file: inputfilename = os.path.join(os.path.dirname(sys.argv[0]), 'tabdelimited.txt') # Strip off the path basefilename = os.path.basename(inputfilename) # Strip off the extension basefilename_noext = os.path.splitext(basefilename)[0] # Get the path of the input file as the target output path targetoutputpath = os.path.dirname(inputfilename) # Generate the output filename outputfilename = os.path.join(targetoutputpath, basefilename_noext+'.xls') # Create a workbook object workbook = xlwt.Workbook() # Add a sheet object worksheet = workbook.add_sheet(basefilename_noext, cell_overwrite_ok=True) # Get a CSV reader object set up for reading the input file with tab delimiters datareader = csv.reader(open(inputfilename, 'rb'), delimiter='\t', quotechar='') # Process the file and output to Excel sheet for rowno, row in enumerate(datareader): for colno, colitem in enumerate(row): worksheet.write(rowno, colno, colitem) # Write the output file. workbook.save(outputfilename) # Open it via the operating system (will only work on Windows) # On Linux/Unix you would use subprocess.Popen(['xdg-open', filename]) os.startfile(outputfilename) The code is also available at the following URL in case the formatting gets eaten by the mail system: http://pastebin.com/APpM7EPf Regards Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
On 11 May 2011 14:34, tee chwee liong tc...@hotmail.com wrote: hi all, thanks for this sharing. when i copy and run this code, i got this error: Traceback (most recent call last): File C:/Python25/myscript/excel/sampleexcel.py, line 1, in module import csv File C:/Python25/myscript/excel\csv.py, line 3, in module w=csv.writer(open('output.csv','w')) AttributeError: 'module' object has no attribute 'writer' Well, reading the error message, it's saying that module csv, coming from file C:/Python25/myscript/excel\ csv.py has no member writer. So, it seems you've called your test script (module) csv which effecitvely hid the standard python csv module. Try renaming your script file to something else ('testcsv.py' maybe) so its name doesn't conflict with the standard csv module and try again. Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
your \ is a / when writing out a string, such as 'C:\test.xls', the / is an escape in python. So you have two choices, You can either write out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path = r'C:\test.xls' the r bit tells python that the following is a regular expression. or regex. You can also use Walter's method above. On Wed, May 11, 2011 at 1:10 PM, tax botsis taxbot...@gmail.com wrote: James, how would you save the workbook into a specific directory? I tried to run that: workbook.save('C:/test.xls') but I get the following error: Traceback (most recent call last): File pyshell#50, line 1, in module wbk.save(C:/test.xls) File C:\Python26\lib\site-packages\xlwt\Workbook.py, line 634, in save doc.save(filename, self.get_biff_data()) File C:\Python26\lib\site-packages\xlwt\Workbook.py, line 615, in get_biff_data self.__worksheets[self.__active_sheet].selected = True IndexError: list index out of range Thanks Tax 2011/5/11 James Reynolds eire1...@gmail.com Slow day at work, so I tried something a little different mostly as a learning exercise for myself, let me know what you all think. I thought it would be useful to have a writer that scales and that organizes the data. For example, you might have 20 tests one day, and 5 the next. I broke up the data into dictionaries where the IDs were keys, and everything that follows is a tuple of testX and result. Instead of iterating through each column, it only writes to the columns where data is present. Disclaimer: I am copying and pasting into Gmail, which sometimes screws up indents. I also put it into pastebin, which was pretty exciting considering I have never used it before: http://pastebin.com/2Dke5FtX import xlwt class Parser: ''' classdocs ''' def __init__(self, test, result): ''' Constructor ''' self.result = result self.test = test self.id = int(self.test[4:]) x = open('test.txt') id_dict = {} for all in x: y = all.split( ) y[-1] = y[-1].strip() id_dict[y[0]] = y[1:] max_test = 0 for key, lists in id_dict.items(): length = len(lists)/2 a = 0 parser_list = [] for items in range(length): t = (lists[a], lists[a+1]) p = Parser(*t) parser_list.append(p) if max_test p.id: max_test = p.id a +=2 id_dict[key] = parser_list workbook = xlwt.Workbook() worksheet = workbook.add_sheet(testruns, cell_overwrite_ok=True) header = 'TEST{0}' headers = ['ID'] range_id = range(max_test +1) for all in range_id[1:]: headers.append(header.format(all)) for i, colno in enumerate(headers): print i, type(i) worksheet.write(0, i, colno) rowno = 1 for keys, values in id_dict.items(): worksheet.write(rowno, 0, keys) for object_lists in values: worksheet.write(rowno, object_lists.id , object_lists.result) rowno +=1 workbook.save(test.xls) On Wed, May 11, 2011 at 9:58 AM, Walter Prins wpr...@gmail.com wrote: On 11 May 2011 14:34, tee chwee liong tc...@hotmail.com wrote: hi all, thanks for this sharing. when i copy and run this code, i got this error: Traceback (most recent call last): File C:/Python25/myscript/excel/sampleexcel.py, line 1, in module import csv File C:/Python25/myscript/excel\csv.py, line 3, in module w=csv.writer(open('output.csv','w')) AttributeError: 'module' object has no attribute 'writer' Well, reading the error message, it's saying that module csv, coming from file C:/Python25/myscript/excel\ csv.py has no member writer. So, it seems you've called your test script (module) csv which effecitvely hid the standard python csv module. Try renaming your script file to something else ('testcsv.py' maybe) so its name doesn't conflict with the standard csv module and try again. Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
On Wed, May 11, 2011 at 1:26 PM, James Reynolds eire1...@gmail.com wrote: your \ is a / when writing out a string, such as 'C:\test.xls', the / is an escape in python. So you have two choices, You can either write out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path = r'C:\test.xls' the r bit tells python that the following is a regular expression. or regex. r means this is 'raw data'. Take each character literally. Raw data does not use \ as a prefix to an escape code. It is just another character You can also use Walter's method above. On Wed, May 11, 2011 at 1:10 PM, tax botsis taxbot...@gmail.com wrote: James, how would you save the workbook into a specific directory? I tried to run that: workbook.save('C:/test.xls') but I get the following error: Traceback (most recent call last): File pyshell#50, line 1, in module wbk.save(C:/test.xls) File C:\Python26\lib\site-packages\xlwt\Workbook.py, line 634, in save doc.save(filename, self.get_biff_data()) File C:\Python26\lib\site-packages\xlwt\Workbook.py, line 615, in get_biff_data self.__worksheets[self.__active_sheet].selected = True IndexError: list index out of range Thanks Tax 2011/5/11 James Reynolds eire1...@gmail.com Slow day at work, so I tried something a little different mostly as a learning exercise for myself, let me know what you all think. I thought it would be useful to have a writer that scales and that organizes the data. For example, you might have 20 tests one day, and 5 the next. I broke up the data into dictionaries where the IDs were keys, and everything that follows is a tuple of testX and result. Instead of iterating through each column, it only writes to the columns where data is present. Disclaimer: I am copying and pasting into Gmail, which sometimes screws up indents. I also put it into pastebin, which was pretty exciting considering I have never used it before: http://pastebin.com/2Dke5FtX import xlwt class Parser: ''' classdocs ''' def __init__(self, test, result): ''' Constructor ''' self.result = result self.test = test self.id = int(self.test[4:]) x = open('test.txt') id_dict = {} for all in x: y = all.split( ) y[-1] = y[-1].strip() id_dict[y[0]] = y[1:] max_test = 0 for key, lists in id_dict.items(): length = len(lists)/2 a = 0 parser_list = [] for items in range(length): t = (lists[a], lists[a+1]) p = Parser(*t) parser_list.append(p) if max_test p.id: max_test = p.id a +=2 id_dict[key] = parser_list workbook = xlwt.Workbook() worksheet = workbook.add_sheet(testruns, cell_overwrite_ok=True) header = 'TEST{0}' headers = ['ID'] range_id = range(max_test +1) for all in range_id[1:]: headers.append(header.format(all)) for i, colno in enumerate(headers): print i, type(i) worksheet.write(0, i, colno) rowno = 1 for keys, values in id_dict.items(): worksheet.write(rowno, 0, keys) for object_lists in values: worksheet.write(rowno, object_lists.id , object_lists.result) rowno +=1 workbook.save(test.xls) On Wed, May 11, 2011 at 9:58 AM, Walter Prins wpr...@gmail.com wrote: On 11 May 2011 14:34, tee chwee liong tc...@hotmail.com wrote: hi all, thanks for this sharing. when i copy and run this code, i got this error: Traceback (most recent call last): File C:/Python25/myscript/excel/sampleexcel.py, line 1, in module import csv File C:/Python25/myscript/excel\csv.py, line 3, in module w=csv.writer(open('output.csv','w')) AttributeError: 'module' object has no attribute 'writer' Well, reading the error message, it's saying that module csv, coming from file C:/Python25/myscript/excel\ csv.py has no member writer. So, it seems you've called your test script (module) csv which effecitvely hid the standard python csv module. Try renaming your script file to something else ('testcsv.py' maybe) so its name doesn't conflict with the standard csv module and try again. Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
your \ is a / when writing out a string, such as 'C:\test.xls', the / is an escape in python. So you have two choices, You can either write out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path = r'C:\test.xls' the r bit tells python that the following is a regular expression. or regex. '/' is perfectly valid Windows separator. See the tested examples below. It works just fine pretty much anywhere I have ever tried it, including the command line. (except apparently for an MSOffice file save dialog that I tried just now) import xlwt workbook = xlwt.Workbook() sheet = workbook.add_sheet('test') sheet.write(0,0,'test') workbook.save('C:/test') workbook.save('C:/test.xls') workbook.save('C:\\test2.xls') workbook.save(r'C:\test3.xls') The error he is getting may be unrelated to actually saving. I am not very familiar with the xlwt, but I know it does not write everything to file on the sheet.write() command. Save() actually does some writing and then saves the file. This can lead to misleading errors. I have had a similar error when writing non-ASCII data (and not changing the default ASCII encoding type). Furthermore, the escape character is '\' not '/', And r'string' means raw string not regular expression. String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences. ~ http://docs.python.org/reference/lexical_analysis.html Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities.___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
Yes, thank you. Actually, I never knew that about the windows separators, since I've just always used the '\' out of habit. On Wed, May 11, 2011 at 2:39 PM, Prasad, Ramit ramit.pra...@jpmchase.comwrote: your \ is a / when writing out a string, such as 'C:\test.xls', the / is an escape in python. So you have two choices, You can either write out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path = r'C:\test.xls' the r bit tells python that the following is a regular expression. or regex. ‘/’ is perfectly valid Windows separator. See the *tested* examples below. It works just fine pretty much anywhere I have ever tried it, including the command line. (except apparently for an MSOffice file save dialog that I tried just now) import xlwt workbook = xlwt.Workbook() sheet = workbook.add_sheet('test') sheet.write(0,0,'test') workbook.save('C:/test') workbook.save('C:/test.xls') workbook.save('C:\\test2.xls') workbook.save(r'C:\test3.xls') The error he is getting may be unrelated to actually saving. I am not very familiar with the xlwt, but I know it does not write everything to file on the sheet.write() command. Save() actually does some writing and then saves the file. This can lead to misleading errors. I have had a similar error when writing non-ASCII data (and not changing the default ASCII encoding type). Furthermore, the escape character is ‘\’ not ‘/’, And r’string‘ means raw string not* *regular expression. “String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called *raw strings* and use different rules for interpreting backslash escape sequences.” ~ http://docs.python.org/reference/lexical_analysis.html Ramit *Ramit Prasad **| JPMorgan Chase Investment Bank | Currencies Technology* *712 Main Street **| Houston, TX 77002* *work phone: 713 - 216 - 5423* This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
On 11-May-11 12:14, James Reynolds wrote: Actually, I never knew that about the windows separators, since I've just always used the '\' out of habit. If you want your code to run everywhere, you should use the functions in os.path to manipulate and build paths. Otherwise, using \ all the time means your code will ONLY ever work on Windows. Using / all the time means your code will work fine on Mac OS X, Linux, or other POSIX systems, and PROBABLY ok on Windows most of the time, but not on other systems. out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path = r'C:\test.xls' the r bit tells python that the following is a regular expression. or regex. Not to be too pedantic, but since this is a tutorial list, I'll point out the more accurate answer so new programmers don't get a mistaken impression. The 'r' string prefix does not actually mean regular expressions. It means raw string where (almost) no backslash codes are recognized in the string constant, so you could say r'C:\test.xls' instead of 'c:\\test.xls'. Raw strings are, however, really useful for strings which hold regular expressions, so you see them in that context a lot. ... ah... and I just noticed that this was pointed out later in the thread. Sorry for the repeat there. ‘/’ is perfectly valid Windows separator. See the *tested* examples below. It works just fine pretty much anywhere I have ever tried it, including the command line. (except apparently for an MSOffice file save dialog that I tried just now) Not... quite. / is accepted by a number of programs, including the Python interpreter, which came from Unix-like systems where / is the directory separator. Very old versions of MSDOS could be configured to use / on the command line for pretty much everything, but that has been deprecated for a long time now (they originally wanted / for command-line switches instead, so used \ for directory separators). Core windows commands don't generally accept it, including native Windows applications (although sometimes they're lenient in what they accept). It'll work for command-line Python script usage because it's *python* that allows them, not *windows*. -- Steve Willoughby / st...@alchemy.com A ship in harbor is safe, but that is not what ships are built for. PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
I'm not contradicting anyone, just relating my experience. I have a large suite of Python programs that run routinely on both Windows and Linux systems. Some of the programs build large directory tree structures. I cast all directory delimiters to the forward slash /. No problems. - Original Message - From: Steve Willoughby st...@alchemy.com To: tutor@python.org Sent: Wednesday, May 11, 2011 12:48 PM Subject: Re: [Tutor] create an xls file using data from a txt file On 11-May-11 12:14, James Reynolds wrote: Actually, I never knew that about the windows separators, since I've just always used the '\' out of habit. If you want your code to run everywhere, you should use the functions in os.path to manipulate and build paths. Otherwise, using \ all the time means your code will ONLY ever work on Windows. Using / all the time means your code will work fine on Mac OS X, Linux, or other POSIX systems, and PROBABLY ok on Windows most of the time, but not on other systems. out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path = r'C:\test.xls' the r bit tells python that the following is a regular expression. or regex. Not to be too pedantic, but since this is a tutorial list, I'll point out the more accurate answer so new programmers don't get a mistaken impression. The 'r' string prefix does not actually mean regular expressions. It means raw string where (almost) no backslash codes are recognized in the string constant, so you could say r'C:\test.xls' instead of 'c:\\test.xls'. Raw strings are, however, really useful for strings which hold regular expressions, so you see them in that context a lot. ... ah... and I just noticed that this was pointed out later in the thread. Sorry for the repeat there. ‘/’ is perfectly valid Windows separator. See the *tested* examples below. It works just fine pretty much anywhere I have ever tried it, including the command line. (except apparently for an MSOffice file save dialog that I tried just now) Not... quite. / is accepted by a number of programs, including the Python interpreter, which came from Unix-like systems where / is the directory separator. Very old versions of MSDOS could be configured to use / on the command line for pretty much everything, but that has been deprecated for a long time now (they originally wanted / for command-line switches instead, so used \ for directory separators). Core windows commands don't generally accept it, including native Windows applications (although sometimes they're lenient in what they accept). It'll work for command-line Python script usage because it's *python* that allows them, not *windows*. -- Steve Willoughby / st...@alchemy.com A ship in harbor is safe, but that is not what ships are built for. PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
Core windows commands don't generally accept it, including native Windows applications (although sometimes they're lenient in what they accept). It'll work for command-line Python script usage because it's *python* that allows them, not *windows*. They work in *Windows* command prompt natively. Some apps do not work well that is true, but the reason that they work like this with Python is NOT because Python allows it but because Windows does. I highly doubt Python checks for / and converts it to \\ (or does any complicated checking of file strings). YMMV for apps, but I have never had a problem with '/' on the command prompt. It is an important caveat to note that this behavior is not Guaranteed. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
On 11-May-11 15:54, Prasad, Ramit wrote: Core windows commands don't generally accept it, including native Windows applications (although sometimes they're lenient in what they accept). It'll work for command-line Python script usage because it's *python* that allows them, not *windows*. They work in *Windows* command prompt natively. Respectfully, I think you aren't clear on how command line execution works. Hopefully I can help a little (yes, there are enough cases where it'll bite you that it's good to know this). Some apps do not work well that is true, but the reason that theywork like this with Python is NOT because Python allows it but because Windows does. I highly doubt Python checks for / and converts it to \\ (or does any complicated checking of file strings). YMMV for apps, but I have never had a problem with '/' on the command prompt. It is an important caveat to note that this behavior is not Guaranteed. Actually, yes, that's exactly what Python (or actually the underlying file handling libraries it's built with) is doing on Windows. There is a decades-long tradition of C compilers (et al) doing this conversion for the sake of all the ported Unix C programs that people wanted to run on Windows (or, at the time, MSDOS). If Windows natively supported it, then you could do this: C:\ DIR /users/fred/desktop C:\ DEL /temp/myfile Or try running your Python program like C:\ /python27/python.exe scriptname.py That doesn't work either, because Windows is NOT in any way at all interpreting the / characters. So why does this work: C:\ myscript.py /temp/myfile /users/fred/desktop or even C:\ \python27\python.exe myscript.py /temp/myfile That works because Windows hands ALL of the argument strings, as-is, with NO interpretation, to the application to deal with. In this case, the application is Python, and Python is going to the extra work to interpret the / characters as \ characters when you try to use them in open() calls and the like. -- Steve Willoughby / st...@alchemy.com A ship in harbor is safe, but that is not what ships are built for. PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an xls file using data from a txt file
excellent it works. tq Date: Wed, 11 May 2011 14:58:39 +0100 Subject: Re: [Tutor] create an xls file using data from a txt file From: wpr...@gmail.com To: tc...@hotmail.com CC: taxbot...@gmail.com; tutor@python.org On 11 May 2011 14:34, tee chwee liong tc...@hotmail.com wrote: hi all, thanks for this sharing. when i copy and run this code, i got this error: Traceback (most recent call last): File C:/Python25/myscript/excel/sampleexcel.py, line 1, in module import csv File C:/Python25/myscript/excel\csv.py, line 3, in module w=csv.writer(open('output.csv','w')) AttributeError: 'module' object has no attribute 'writer' Well, reading the error message, it's saying that module csv, coming from file C:/Python25/myscript/excel\ csv.py has no member writer. So, it seems you've called your test script (module) csv which effecitvely hid the standard python csv module. Try renaming your script file to something else ('testcsv.py' maybe) so its name doesn't conflict with the standard csv module and try again. Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor