[Tutor] split on tab and new line

Kent Johnson kent_johnson at skillsoft.com
Fri Sep 3 22:20:56 CEST 2004


You can't directly split the text from the file in two ways at once. You 
could iterate over the lines in the files and build the lists you want, but 
that isn't the approach I would take, for a couple of reasons
- you are throwing away some data that you need
- with a dictionary, you can keep the extra data from file1 and have easy 

I would try something like this:
for each line in file1:
   split the line into the initial letter (the key) and everything else (data1)
   put the key and data into a dictionary

for each line in file2:
   split the line into the initial letter (the key) and everything else (data2)
   look up the new key in the dictionary. If it is there, you will get the 
file1 data back.
   Now you have everything you need to print out what you want. (data1 and 

If you need help with the individual steps, let us know.

At 11:10 AM 9/3/2004 -0700, kumar s wrote:
>Dear group,
>I have a file1:
>A 12 13 [please read one space is one tab here]
>B 24 90
>C 34 45
>File 2:
>A Apple
>B Boy
>Now I want to check if A in file2 is existing in
>File1, if then, I want to print corresponding element
>of A in File2, Apple and corresponding value of A in
>Desired output:
>Apple 12 13
>Boy 24 90
>My plan:
> >f1 = open('file1.txt','r')
> >f2 = open('file2.txt','r')
> >x = f1.read()
> >y = f2.read()
> >list1 = split(x,'\t','\n')
>here I want to split f1 on both tab and new line just
>to get only column 1 of file1. In this case
>list1 = ['A','B','C']
>Similar operation for list2.
>Now I have list1 and list2.
> >for i in list1:
>       for s in list2:
>           if i == s:
>             m = m.append(i)
>           else:
>              print "i did not find i"
>My question:
>1. Is it possinble to split a file on both tab and new
>line. This is to get only column 1 of any matrix. If
>there is some better method please suggest
>2. Is my process good. I dont know myself.
>3. How can I append the values of A in file 1 to names
>(column 2 of file 2).
>Apple 12 13 ( how can I make Apple print next to
>Please help.
>Thank you.
>Do You Yahoo!?
>Tired of spam?  Yahoo! Mail has the best spam protection around
>Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list