0
import os
for file in ['a.txt', 'b.txt', 'c.txt']:
    if not os.path.exists(os.getcwd() + '\\' + file):
        print(fr'{file} is missing')

Basically, I would like to place a.txt, b.txt, c.txt into the os.path.exists function one by one, and then, inside the if clause, I would like to print the message with the file name included. I have no idea how to make it pythonic. I see people write "in" with "if" in one line, but I have no idea how to do that in my case, as I have a print function that uses the value "file" too.

Again, I want to make it efficient, pythonic.

4
  • You will need a for loop as you are trying to check if each file exists or not. Commented Mar 4, 2021 at 6:52
  • It's pretty Pythonic to me. It's easy to read and understand and I'm not sure what you seek to achieve with changing it. Commented Mar 4, 2021 at 6:54
  • 1
    It seems like you're thinking of if file in ('a.txt', 'b.txt', 'c.txt'): but that's testing something completely different. Commented Mar 4, 2021 at 6:55
  • 1
    Your code is about as good as it can get. Commented Mar 4, 2021 at 6:56

2 Answers 2

1

It's not clear what you mean by "pythonic". One thing which would be that is to use modern stdlib modules e.g. pathlib:

from pathlib import Path
for file in ['a.txt', 'b.txt', 'c.txt']:
    if not (path.cwd() / file).exists():
        print(fr'{file} is missing')

Not using unnecessary bits is probably pythonic as well: the r string prefix is completely unnecessary.

You could also go the functional route, but AFAIK it's not really favored. It could be used to "merge" some of the complicated bits together, as well as avoid repeated calls to cwd, though:

from pathlib import Path
for file in map(path.cwd().joinpath, ['a.txt', 'b.txt', 'c.txt']):
    if not file.exists():
        print(f'{file.name} is missing')

I would also avoid the name file: I'd assume it to be an actual file object (aka the output of open), but that's more of a personal thing.

Sign up to request clarification or add additional context in comments.

1 Comment

Best comment ever seen, really want to double tick your answer, though stackoverflow does not have that function.
0

You could use os.path.join function instead of concatenation:

import os
for file in ['a.txt', 'b.txt', 'c.txt']:
    if not os.path.exists(os.path.join(os.getcwd(), file)):
        print(fr'{file} is missing')

Comments

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.