How to open file when filename contains command prompt substring in Windows

153 views Asked by At

Sometimes, we need to generate filenames with current date in their file names. Windows command prompt supports variable substrings. For example, my command prompt prints 2021_25_02.txt for command echo %DATE:~10,4%_%DATE:~7,2%_%DATE:~4,2%.txt. The output is based on my Regional settings.

I thought this is natively supported by Windows, but it turned out it is not. I assumed the following code will natively work in python, but it raises exception:

>>> fh = open(r'j:\%DATE:~10,4%_%DATE:~7,2%_%DATE:~4,2%.txt', 'w')
IOError: [Errno 22] invalid mode ('w') or filename: 'j:\\%DATE:~10,4%_%DATE:~7,2%_%DATE:~4,2%.txt'

I am able to do workaround with subprocess module as follows:

>>> import subprocess
>>> name = r'j:\%DATE:~10,4%_%DATE:~7,2%_%DATE:~4,2%.txt'
>>> final_name = subprocess.Popen(['echo', name], stdout=subprocess.PIPE, shell=True).communicate()[0].strip()
>>> print(final_name)
j:\2021_25_02.txt

Is there more simple or pythonic way to make command prompt variable substrings work?

0

There are 0 answers