[Tutor] How to extract data from text to excel?

Steven D'Aprano steve at pearwood.info
Fri Mar 4 01:55:13 CET 2011


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 0011110 011011110"
 >>> L.split()
['001110101', '0011110', '011011110']

You get a list of strings. If there is no whitespace in the string, you 
get a list containing one string:

 >>> L = "0011101010011110011011110"
 >>> L.split()
['0011101010011110011011110']


> 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


More information about the Tutor mailing list