A client asked me about help on a Python script. I jumped into my seat and excited typed “OF COURSE!!”, more excited than Dug getting to play fetch.
She was using Python to run a DOS command. This isn’t a horrible way to do things, actually, it is a horrible way to do things so I tried to ween her off this and use a more Pythonic way of doing it. (Okay, full disclosure, I use this for my scripts so they stay live after they’re finished:)
os.system("pause")
I didn’t get the entire code, but this was what she eventually came up with that worked:
subprocess.call(["dir"+"/O:-D/A:-D",bookingFilePath1, ">>","tmp2.txt"], shell=True )
It’s cool that she’s using the subprocess but this isn’t the “Python” way of doing things. At the very least, if you get the result you need without a bug then that should suffice. But being a Pythonista means delving deeper until you come up with the most Python-like solution.
What I came up with is the following, which worked perfectly and is mostly Pythonic:
import os
targpath = "C:\\users\\ReedActed\\desktop\\" # To direct location of target file
with open(targpath + 'P-drive-test.txt', 'w', encoding='utf-8') as outfile:
for r, d, f in os.walk('P:\\backup\\'):
for file in f:
fileneat = os.path.join(r, file) + "\n"
outfile.write(fileneat)
Regrettably, she found out what her error was and continued to use the DOS command in Python rather than use Python’s native libraries. *SIGH*