ded
ded

Reputation: 430

python use for loop to modify list of variables

I have a script using argparse to gather a list of user defined directories. On the command line they may or may not specify a trailing "/" symbol. I'd like to do something up front so that all variables have the trailing "/" so I can reliably do:

# What I want:
with open(args.a + filename, "w") as fileout:
    #do stuff
    print('whatever', file=fileout)

rather than having to include an extra "/" in the name like this:

# What I have:
with open(args.a + "/" + filename, "w") as fileout:
    #do stuff
    print('whatever', file=fileout)

I also know that dir/ect/ory and dir//ect//ory are nearly equivalent save some fringe cases which are not applicable, but putting + "/" + all over the place seems wrong/wasteful.

In attempting to make a small function to run on all relevant variable I'm only seeing the desired outcome when I explicitly call the function on the variable not on a list containing the elements.

def trailingSlash(x):
if x.endswith("/"):
    return x
else:
    return x + "/"

a = 'ok/'
b = 'notok'
c = 'alsonotok'

for _ in [a, b, c]:
    _ = trailingSlash(_)

print(a,b,c)  #gives ok/ notok alsonotok

c = trailingSlash(c)
print(c)  #gives alsonotok/

I understand why changing a list as you are iterating over it is generally bad, and understand that in the for loop the iterator is not actually pointing to a, b, or c. I also know if I wanted the values in a new list i could do something like [trailingSlash(x) for x [a,b,c]] but I need to maintain the a,b,c handle. in I know that I can also solve this by specifically calling x = trailingSlash(x) on every individual variable, but seems like there should be a better way. Any solutions I'm missing?

Upvotes: 0

Views: 36

Answers (1)

Green Cloak Guy
Green Cloak Guy

Reputation: 24711

You can use os.path.join() to ignore the whole issue. It behaves no matter whether there are slashes at the end or not, and is platform-independent as a bonus (that is, it uses \\ instead of / when running on Windows, for example):

import os
...
os.path.join("dir/", "ect", "ory")
# "dir/ect/ory" on Unix, "dir\\ect\\ory" on Windows

In your case you'd want to do

with open(os.path.join(args.a, filename), "w") as fileout:
    ...

Upvotes: 1

Related Questions