0

I am having trouble splitting an '&' in a list of URL's. I know it is because I cannot split a list directly but I cannot figure out how to get around this error. I am open for any suggestions.

def nestForLoop():
    lines = open("URL_leftof_qm.txt", 'r').readlines()
    for l in lines:
        toke1 = l.split("?")
        toke2 = toke1.split("&")
        for t in toke2:
            with open("ampersand_right_split.txt".format(), 'a') as f:
                    f.write
    lines.close()

nestForLoop() 
0

2 Answers 2

8

NO. STOP.

qs = urlparse.urlparse(url).query
qsl = urlparse.parse_qsl(qs)
Sign up to request clarification or add additional context in comments.

Comments

1

As Ignacio points out, you should not be doing this in the first place. But I'll explain where you're going wrong, and how to fix it:

toke2 is a list of two strings: the main URL before the ?, and the query string after the &. You don't want to split that list, or everything in that list; you just want to split the query string. So:

mainurl, query = l.split("?")
queryvars = query.split("&")

What if you did want to split everything in the first list? There are two different things that could mean, which are of course done differently. But both require a loop (explicit, or inside a list comprehension) over the first list. Either this:

tokens = [toke2.split("&") for toke2 in l.split("?")]

or

tokens = [token for toke2 in l.split("?")
          for token in toke2.split("&")]

Try them both out to see the different outputs, and hopefully you'll understand what they're doing.

4 Comments

I'm getting a Value error. Probably because there is code in my file that does not have an & on some lines. How can I fix this?
Having lines without a & wouldn't raise anything, but a line without a ? would. Change the first line to mainurl, _, query = l.partition('?').
It splits on the '?' but not on the '&'.
@MichaelJerzyRegdosz: If you're actually using the code I wrote above, splitting on the ? but not the & will not raise a ValueError; you'll successfully get a 1-element list in queryvars. So, either you're wrong, and it's the ? that's missing, or you wrote different code than what I showed, in which case I can't debug code that I haven't seen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.