471,595 Members | 1,092 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,595 software developers and data experts.

file to nested list

I'm having alot of troubles with this...so basically i am given a file for example:

File =


and basically the output is supposed to be [[">123" , "qwerty"] , [">567" , "tyuiuy"] , ["987" , "poiuyt"]]

i have no idea how to do that can someone help me please?.
Mar 16 '09 #1
12 3707
I'm assuming you know basic file I/O?

Basically, what you need to do is create an empty list (let's call it 'root'), open the file you want with open() (let's call this 'file'), then have a loop where you get two lines at a time using file.readline() (store these in two separate variables, 'a' and 'b' for example). Then you need to do root.append([a, b]), where [a, b] will end up being [">123" , "qwerty"] from your example. When there are no more lines to read, stop the loop, and there you have your list (root).

Does that make any sense?
Mar 16 '09 #2
yep that makes a lot of sense, and i understand fully what your trying to say except i forgot to say that the file could also be

file =


output = [[">123" , "qwertyioweio"] , [">567" , "tyuiuy"] , ["987" , "poiuyt"]]

the output for >123 is "qwertyioweio" because for simplicity's sake i made the file look that way to look simple, so basically after "qwerty" it went to a new line because it was full. i hope that made sense....

also is there a way to use a for loop for this question?
Mar 16 '09 #3
Oh I see. Well in that case, you're going to need to make a temporary list for each "sub list," and if the line starts with '>', make that line the first part of the list, and vice versa. Then just append that list to the 'root'.

You could use a for loop, although it would be easier not to. Is this for an assignment? If you have to use a for loop, then you could read the file all at once into a string and split() it by newlines, and then loop through each line (for line in lines:, or something like that).

EDIT: Actually, now that I think about it, the way I just mentioned would probably be simpler haha.
Mar 16 '09 #4
is your way by using a while loop?...=S(which i hate)..
Mar 16 '09 #5
Yeah, the first method I mentioned would use a while loop (it was the first thing that popped into my head since that's how I learned it), but I guess using a for loop would, in the end, be much simpler and cleaner. Go for the 'for' loop. :)
Mar 16 '09 #6
2,851 Expert Mod 2GB
Let us assume that you have read the file using file object method readlines().
Expand|Select|Wrap|Line Numbers
  1. data = ['>123\n', 'qwerty\n', 'ioweio\n', '>567\n', 'tyuiyuy\n', '>987\n', 'poiuyt\n']
  3. output = []
  5. for item in data:
  6.     if item.startswith('>'):
  7.         output.append([item.strip(), ''])
  8.     else:
  9.         output[-1][1] += item.strip()
  11. print output
>>> [['>123', 'qwertyioweio'], ['>567', 'tyuiyuy'], ['>987', 'poiuyt']]
Mar 16 '09 #7
i think im close...can you debug my code

Expand|Select|Wrap|Line Numbers
  1. import urllib
  3. def qwerty(f):
  5.     a = urllib.urlopen(f)
  6.     s = ""
  7.     l = a.readlines()
  8.     y = s.join(l)
  9.     #p = y.replace('\r', "")
  10.     q = y.split('\r')
  12.     output = [] 
  14.     for item in q: 
  15.         if item.startswith('>'): 
  16.             output.append([item.strip(), '']) 
  17.         else: 
  18.             output[-1][1] += item.strip() 
  20.     print output 
and the output that comes out when i test it with

Expand|Select|Wrap|Line Numbers
  1. qwerty("http://www.utsc.utoronto.ca/~szamosi/a20/assignments/a3/starter/sequences.txt")
is it will give me the whole thing as a list within a list, it doesnt seperate the numbers within...because in you "data" string the \n appears after the string whereas in mine it appears before..i think =s
Mar 16 '09 #8
2,851 Expert Mod 2GB
You have made it too complicated. There is no need to join, split, or replace. String method strip() will remove all leading and training whitespace. You created an open file object, but never closed it. You should try to make your variable names more descriptive instead of using single letters. In my example, variable data is comparable to your variable l.

Mar 16 '09 #9
ah ok now i see...thanks for your repliess!!
Mar 16 '09 #10
469 Expert 256MB
Sorry, bvdet, but read this. How about calling it file_lines instead?
Mar 16 '09 #11
2,851 Expert Mod 2GB
That would work. I sometimes name a variable of short duration, such as an open file object (f) or loop counter (i), with a single letter. Stringing several in a row makes the code unreadable. I might do something like this:
Expand|Select|Wrap|Line Numbers
  1. def qwerty(fn): # fn for file name
  3.     f = urllib.urlopen(fn) # **EDIT**
  4.     fList = a.readlines() # or lineList or line_list or lines
  5.     f.close()
Mar 17 '09 #12
469 Expert 256MB
Yeah, all my loop variables are called i, j, k, l, m, n, o, etc. It makes my nested loops unreadable.
Wow, urllib is a built in library I can use! I had no idea.
Mar 18 '09 #13

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by Lee K. Seitz | last post: by
11 posts views Thread by mlf | last post: by
2 posts views Thread by neildunn | last post: by
2 posts views Thread by alexandre_irrthum | last post: by
7 posts views Thread by patrick j | last post: by
reply views Thread by XIAOLAOHU | last post: by
reply views Thread by Anwar ali | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.