Reputation: 99
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.
Upvotes: 0
Views: 80
Reputation: 42197
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.
Upvotes: 1
Reputation: 901
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')
Upvotes: 0