[Tutor] How to extract data from text to excel?
hi, i found a module called xlwt (http://www.python-excel.org/) that can write to Excel. i want the code to read from a file (robert.txt) and then write to excel in a column. for eg: cell col0, row0 = 0 cell col0, row1 = 0 cell col0, row2 = 0 cell col0, row3 = 1 cell col0, row4 = 0 cell col0, row5 = 1 however, it seems that the output from this code is that it only writes to one cell in the excel. Pls advise how to modify the code. Pls advise if there are alternative way for python to do this task? tq import xlwt # Create workbook and worksheet wbk = xlwt.Workbook() sheet = wbk.add_sheet('python') row = 0 # row counter f = open('robert.txt') for line in f: # separate fields by commas L = line.strip() sheet.write(row,0,L) row += 1 wbk.save('reformatted.data.xls') thanks tcl 01010100010110111011101100110011001100001100110001000110001101111011010110001101000110001000110001000110001000110001000110001000110101001001100101100110010101010101010101010101001000111100011101110100010001110011101010111011011100011101001110001000100100111010101110011101___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A class that instantiates conditionally ?
David wrote: class MyClass_2(object): def __new__(self, condition): if condition: return object.__new__(self) else: return None [...] Spot on. It would require two "if" tests, one inside __new__() and another in the code. You will always need at least two if tests: once in the function producing the result ("does the test succeed? if not, return this instead...") and once in the code using the result ("did the magic value get returned?"). Consider str.find()... the caller has to check whether it returns -1, but the find method itself has to check whether the search string is found or not, and return -1 if it is not. This may or may not require a *literal* if statement, but there's still an implied test in the code. I found your mention of try/except there especially helpful, because it was a pertinent reminder that I was not thinking in "ask forgiveness not permission" mode. This (newbie mistake) occurred because I wanted my application to continue, not abort with an exception, but after your prompt I recalled that "except" doesn't have to raise exceptions it can do other things. Fair enough, and arguably having the class raise an exception is a better design, but with all the people saying your original design was "too clever", I'd like to give it some love :) I think the design is just clever enough. I would consider using it if I were designing something like the regular expression match and search methods, which return None if the regex doesn't match. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to extract data from text to excel?
tee chwee liong wrote: hi, i found a module called xlwt (http://www.python-excel.org/) that can write to Excel. i want the code to read from a file (robert.txt) and then write to excel in a column. for eg: cell col0, row0 = 0 cell col0, row1 = 0 cell col0, row2 = 0 cell col0, row3 = 1 cell col0, row4 = 0 cell col0, row5 = 1 however, it seems that the output from this code is that it only writes to one cell in the excel. That's because your data ("robert.txt") only contains one line with one field. You read that one field as a big chunk of text, and then write it to one cell, and then the loop ends. import xlwt # Create workbook and worksheet wbk = xlwt.Workbook() sheet = wbk.add_sheet('python') row = 0 # row counter f = open('robert.txt') for line in f: # separate fields by commas What does this comment mean? You don't have any commas in the file "robert.txt", and you don't actually do anything with or to commas in your code. I think that comment is false. L = line.strip() sheet.write(row,0,L) Here you write the entire contents of the file into one cell. You need to iterate over L: for c in L: sheet.write(row, 0, c) row += 1 -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to extract data from text to excel?
On Thu, Mar 3, 2011 at 9:10 AM, Steven D'Aprano wrote: > tee chwee liong wrote: > >> hi, >> i found a module called xlwt (http://www.python-excel.org/) that can >> write to Excel. i want the code to read from a file (robert.txt) and then >> write to excel in a column. for eg: >> cell col0, row0 = 0 >> cell col0, row1 = 0 >> cell col0, row2 = 0 >> cell col0, row3 = 1 >> cell col0, row4 = 0 >> cell col0, row5 = 1 >> >> however, it seems that the output from this code is that it only writes to >> one cell in the excel. >> > > That's because your data ("robert.txt") only contains one line with one > field. You read that one field as a big chunk of text, and then write it to > one cell, and then the loop ends. > > > import xlwt >> # Create workbook and worksheet wbk = xlwt.Workbook() sheet = >> wbk.add_sheet('python') >> row = 0 # row counter >> f = open('robert.txt') >> for line in f: # separate fields by commas >> > > What does this comment mean? You don't have any commas in the file > "robert.txt", and you don't actually do anything with or to commas in your > code. I think that comment is false. > > > L = line.strip()sheet.write(row,0,L) >> > > Here you write the entire contents of the file into one cell. You need to > iterate over L: > >for c in L: >sheet.write(row, 0, c) >row += 1 > > > > -- > Steven > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I might not understand what you need to do, but it seems to me that its simpler to create a csv file that can be read by excel. Actually, since you have only one field per row, there are no commas. Here is what I came up with: #!/usr/bin/env python """ Read a file containing a long string of ones and zeros Separate each bit with a comma, then write the whole csv thing to an output file. This can be read by an excel like application with one bit in each row of the first column """ f = open('./robert.txt','r') f_data = f.read() list_of_bits = list(f_data) csv_string = '\n'.join(list_of_bits[:-1]) # these 3 lines show what is going on print f_data print list_of_bits print csv_string f_out = open('./robert.csv', 'w') f_out.write(csv_string) f_out.close() -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help!
okay so this is my comp sci lab * Problem: *ProductionTime.py It takes exactly 2 minutes and 7 second to produce an item. Unfortunately, after 143 items are produced, the fabricator must cool off for 5 minutes and 13 seconds before it can continue. Write a program that will calculate the amount of time required to manufacture a given number of items. * Output: *Output the amount of time D days HH:MM:SS * Sample Input : * numItems =1340 Represents the numbers items to be manufactured * Sample Output : * 2 days 00:03:17 this is the coding i have written for it! numitems= int(raw_input("Enter the number of items needed to be manufactured:")) seconds=numitems*127 m, s = divmod(seconds, 60) h, m = divmod(m, 60) print "%d:%02d:%02d" % (h, m, s) but how would i add the 5 min and 13 seconds after 143 items have been produced??? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help!
Am 03.03.2011 22:28, schrieb Andrew Bouchot: okay so this is my comp sci lab * Problem: *ProductionTime.py It takes exactly 2 minutes and 7 second to produce an item. Unfortunately, after 143 items are produced, the fabricator must cool off for 5 minutes and 13 seconds before it can continue. Write a program that will calculate the amount of time required to manufacture a given number of items. * Output: *Output the amount of time D days HH:MM:SS * Sample Input : * numItems =1340 Represents the numbers items to be manufactured * Sample Output : * 2 days 00:03:17 this is the coding i have written for it! numitems= int(raw_input("Enter the number of items needed to be manufactured:")) seconds=numitems*127 m, s = divmod(seconds, 60) h, m = divmod(m, 60) print "%d:%02d:%02d" % (h, m, s) but how would i add the 5 min and 13 seconds after 143 items have been produced??? For any given number of item, how many cool-down periods do you have in total? What's the prodcution time without cooling? ---||---||--||-- producing |cooling |producing |cooling |producing |cooling |producing HTH, Jan ___ 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] Help!
This isn't so much as a python problem as it is a simple math problem, and I feel you are being lazy, but in the offchance you're having problems with the '/' operator: cooloff = (numitems/143)*313 total = cooloff + seconds I think you are using python 2.6 (and I guess 2.7) or older based on your print statement. I could be totally wrong, in which case numitems/143 will not work correctly. In 2.6 and older the / operator does floor division. You are almost assuredly going to get flamed for not having a descriptive title and for asking what is obviously homework questions On Thu, Mar 3, 2011 at 4:28 PM, Andrew Bouchot wrote: > okay so this is my comp sci lab > > * > > Problem: > *ProductionTime.py It takes exactly 2 minutes and 7 second to produce an > item. Unfortunately, after 143 items are produced, the fabricator must cool > off for 5 minutes and 13 seconds before it can continue. Write a program > that will calculate the amount of time required to manufacture a given > number of items. * > > Output: > *Output the amount of time D days HH:MM:SS * > > Sample Input : > * > > numItems =1340 Represents the numbers items to be manufactured > * > > Sample Output : > * > > 2 days 00:03:17 > > > > this is the coding i have written for it! > > numitems= int(raw_input("Enter the number of items needed to be > manufactured:")) > seconds=numitems*127 > m, s = divmod(seconds, 60) > h, m = divmod(m, 60) > print "%d:%02d:%02d" % (h, m, s) > > but how would i add the 5 min and 13 seconds after 143 items have been > produced??? > > ___ > 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] Help!
On Thu, Mar 3, 2011 at 4:56 PM, Knacktus wrote: > Am 03.03.2011 22:28, schrieb Andrew Bouchot: >> >> okay so this is my comp sci lab >> * >> >> Problem: >> >> *ProductionTime.py It takes exactly 2 minutes and 7 second to produce an >> item. Unfortunately, after 143 items are produced, the fabricator must >> cool off for 5 minutes and 13 seconds before it can continue. Write a >> program that will calculate the amount of time required to manufacture a >> given number of items. * >> >> Output: >> >> *Output the amount of time D days HH:MM:SS * >> >> Sample Input : >> >> * >> >> numItems =1340 Represents the numbers items to be manufactured >> >> * >> >> Sample Output : >> >> * >> >> 2 days 00:03:17 >> >> this is the coding i have written for it! >> >> numitems= int(raw_input("Enter the number of items needed to be >> manufactured:")) >> seconds=numitems*127 >> m, s = divmod(seconds, 60) >> h, m = divmod(m, 60) >> print "%d:%02d:%02d" % (h, m, s) >> >> but how would i add the 5 min and 13 seconds after 143 items have been >> produced??? > > For any given number of item, how many cool-down periods do you have in > total? > What's the prodcution time without cooling? > > ---||---||--||-- > producing |cooling |producing |cooling |producing |cooling |producing > Maybe I understood it wrong, but they ask "but how would i add the 5 min and 13 seconds after 143 items have been produced???", which is produce 143, then wait 5:13. Those times are irrelevant, unless the need is in between the produced 143, which would make the pseudo: > count = 0 > while count != 144 >do stuff time.sleep(5:13/143 interval) count += 1 > HTH, > > Jan > >> >> >> >> ___ >> 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 > -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Homework Problem Flaming (was: Help!)
On 03/03/2011 04:58 PM, James Reynolds wrote: > You are almost assuredly going to get flamed for not having a descriptive > title and for asking what is obviously homework questions > Maybe for not having a descriptive title, but there's nothing wrong with coming to the list with homework! The requirements are that you've put some work into it, you show your code, you say what is should be doing that it isn't, and that you explain what you've tried doing previously. At least, those are what I look for. Even better that he said right up front that it was homework. With homework problems, instead of saying "Hey, replace lines 42-48 with foo", saying "Look into the bar module, it bazifies the proper value for you". Teaching people to learn better for themselves instead of hand-feeding them the answers. This list does a really good job with it, IMO. -- Corey Richardson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help!
James Reynolds wrote: [...] You are almost assuredly going to get flamed for not having a descriptive title and for asking what is obviously homework questions At least Andrew did the right thing by being honest that it was a homework question, and by showing the work he's done so far. But yes, you're right, a more descriptive title is always appreciated. And speaking for flaming, thank you for not top-posting in the future. If you *must* top-post, because you're using one of those stupid "smart" phones that won't let you do otherwise, at least apologize for doing so. Andrew, you ask: but how would i add the 5 min and 13 seconds after 143 items have been produced??? You should always do all your calculations in a single unit of time (probably seconds), and only convert back to D HH:MM:SS at the very end. If you have N items to produce, you need to consider it broken up into groups of 143 items, plus cooling off time *between* each group. If N is an exact multiple of 143 items, you have something like this: (143)(cool)(143)(cool)(143)(cool)(143)(cool)(143) Notice that you don't care about the cooling off time after you're done. If N is not an exact multiple, there will be some remainder: (143)(cool)(143)(cool)(143)(cool)(143)(cool)(143)(cool)(remainder) You can work out the number of groups of 143, and the remainder left over, using the divmod function. Then you can work out the number of cooling periods -- this is just the fence post problem. If you have a fence with N posts |===|===|===|===|===|===|===|===|===| how many sections are there? Or conversely, given M sections of a fence, how many posts do you need? -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to extract data from text to excel?
> What does this comment mean? You don't have any commas in the file > "robert.txt", and you don't actually do anything with or to commas in > your code. I think that comment is false. > > > L = line.strip() > > sheet.write(row,0,L) > > Here you write the entire contents of the file into one cell. You need > to iterate over L: > > for c in L: > sheet.write(row, 0, c) > row += 1 hi steven, ok i get what you meant. there are no pattern to split the entire contents in the robert.txt. is the content still needed to be splitted? L = line.split() will result in one long string. could you pls explain what is c? how do i modify the c in the code? pls advise. tq for line in f: #for c in L: L = line.split() print L sheet.write(row,0) row += 1 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to extract data from text to excel?
tee chwee liong wrote: What does this comment mean? You don't have any commas in the file "robert.txt", and you don't actually do anything with or to commas in your code. I think that comment is false. L = line.strip() sheet.write(row,0,L) Here you write the entire contents of the file into one cell. You need to iterate over L: for c in L: sheet.write(row, 0, c) row += 1 hi steven, ok i get what you meant. there are no pattern to split the entire contents in the robert.txt. is the content still needed to be splitted? L = line.split() will result in one long string. Do not confuse split() and strip() methods. This is easy to do, even for native English speakers, so be extra careful. In your earlier code, you used strip(), which removes leading and trailing whitespace: >>> L = ' 0001110011 \n' # ends with a newline >>> L.strip() '0001110011' Compare split: >>> L = "001110101 000 01100" >>> L.split() ['001110101', '000', '01100'] You get a list of strings. If there is no whitespace in the string, you get a list containing one string: >>> L = "00111010100001100" >>> L.split() ['00111010100001100'] could you pls explain what is c? how do i modify the c in the code? The interactive interpreter is your best friend in the world. You should learn to use it to answer simple questions, and count yourself lucky that Python has an interactive interpreter. Not all languages do. >>> L = "001110" >>> for c in L: ... print c ... 0 0 1 1 1 0 c is just a name like any other name: >>> L = "001110" >>> for c in L: ... if c == '1': ... c = 'Surprise!' ... print c ... 0 0 Surprise! Surprise! Surprise! 0 -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to extract data from text to excel?
thanks Steven, i get what you mean now. final code works: import xlwt """Reads robert.txt""" # Create workbook and worksheet wbk = xlwt.Workbook() sheet = wbk.add_sheet('python') row = 0 # row counter f = open('robert.txt') L = line.strip() for c in L: sheet.write(row,0,c) row += 1 wbk.save('reformatted.data.xls') thanks tcl ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Need some help on output
I am creating a dictionary by parsing a text file. The code is below: backup_servers = {} fo = open('c:/test/backup_shares.txt') for line in fo: backup_server = line.split(',') backup_servers[backup_server[0]]=backup_server[1] for i, v in backup_servers.items(): backup_shares = i archive_dir = v archive_dir += '/' archive_dir += str(today) archive_dir += '.txt' I need to use the output from the above with the win32.py modules to map drives and then create a file name with timestamp appended to it for backups that I'm doing and database dumps. The problem is that it's output like so: c:/test /backup_name_2011-03-03.txt \\server_name1\backup_share c:/test /backup_name_2011-03-03.txt \\server_name1\backup_share I've tried this several ways and using a print command as so: print backup_shares, archive_dir print '%s %s' %( backup_shares, archive_dir) and it still inserts a new line The contents of the file are just: \\server_name1\backup_share$,c:/test \\server_name1\backup_share$,c:/test I tried including the backup slashes in the text file, omitting them and including them in the print statement, to no avail. Any comments? Becky ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need some help on output
On Fri, Mar 4, 2011 at 6:48 AM, Becky Mcquilling wrote: > I am creating a dictionary by parsing a text file. > > The code is below: > backup_servers = {} > fo = open('c:/test/backup_shares.txt') > for line in fo: > backup_server = line.split(',') > backup_servers[backup_server[0]]=backup_server[1] Looping over a file object returns lines including the trailing newline. If that's not required, you have to remove the newline at the end yourself using the strip method. To see the behaviour, print out the value of line at the start of the loop body. Documentation on file objects: http://docs.python.org/library/stdtypes.html#file-objects Documentation on strings: http://docs.python.org/library/stdtypes.html#string-methods > -- regards, kushal ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need some help on output
Thanks, that helped. I took a second look and realized where I had tried calling the .strip() method was wrong. Appreciate the pointer. Becky On Thu, Mar 3, 2011 at 5:37 PM, Kushal Kumaran < kushal.kumaran+pyt...@gmail.com> wrote: > On Fri, Mar 4, 2011 at 6:48 AM, Becky Mcquilling > wrote: > > I am creating a dictionary by parsing a text file. > > > > The code is below: > > backup_servers = {} > > fo = open('c:/test/backup_shares.txt') > > for line in fo: > > backup_server = line.split(',') > > backup_servers[backup_server[0]]=backup_server[1] > > Looping over a file object returns lines including the trailing > newline. If that's not required, you have to remove the newline at > the end yourself using the strip method. > > To see the behaviour, print out the value of line at the start of the loop > body. > > Documentation on file objects: > http://docs.python.org/library/stdtypes.html#file-objects > Documentation on strings: > http://docs.python.org/library/stdtypes.html#string-methods > > > > > -- > regards, > kushal > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor