0

Hi guys I have question about global variable. How can I put filename into varibale and call it on global. My code:

for filename in dirs:
    if filename.startswith("EPG_NatGeo"):
            z = filename


output_file = open('nat.xml','w') 
with open (r'{}','r').format(z) as file:

How can varibale became file for opening? Thx for reading this post!

1
  • And what error do you see when you run this code? Commented Oct 3, 2013 at 8:36

1 Answer 1

2

You don't need to use .format() at all here:

with open(z, 'r') as file:

and even if you did, you'd call it on the string object, not the open file:

with open('foo_{}_bar'.format(z), 'r') as file:

Note that z is re-bound in your loop more than once if multiple filename values match your .startswith() test, you'll only be passing the last match to open(). If no values match you run the risk of z never having been bound at all and you'll get a NameError exception instead.

Use break to pick the first match, and use else: on the for loop to detect that no match was made:

for filename in dirs:
    if filename.startswith("EPG_NatGeo"):
        z = filename
        break
else:
    raise ValueError('No filename matched')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Martijn Pieters for answer! You helped me out!

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.