user246185
user246185

Reputation: 156

Batch Exclamation Mark Variable

I'm converting a Batch script to Python. I got stuck here:

setlocal EnableDelayedExpansion

for /F %%x in ('dir /B/D %OPATH%') do (
    set "FILENAME=!FILENAME! %%x"
)

I don't understand what

set "FILENAME=!FILENAME! %%x"

does.

Upvotes: 1

Views: 825

Answers (3)

lit
lit

Reputation: 16236

The batch script is producing a space separated list of the OPATH directory file names. It is easy enough to use Python glob to get the same thing as a list.

import os
import glob
dlist = glob.glob(os.environ['OPATH'] + os.sep + '*')

This will produce a list of file names. Directory names will have an os.sep at the end of them. This might be easier for your Python code to handle than a single string with space separators.

If you must have a space delimited string they can easily be joined.

dstring = ' '.join(dlist)

Upvotes: 1

user6811411
user6811411

Reputation:

The for loop concatenates all found dir entries to one string.

BTW the /B of dir overrides the /D, so it can be omitted.

Also the default for /f options "tokens=1 delims= " will truncate file names with spaces.

Magoo explained the other issues fine.

Upvotes: 2

Magoo
Magoo

Reputation: 80033

Normally, %var% retrieves the value of var.

Within a code block (a parenthesised series of lines), %var% will be replaced by the value of var when the statement invoking the block (a for or an if) was encountered, not the value of var as it varies due to the operation of the block (the run-time value).

When delayedexpansion is invoked, %var% still returns the original, parse-time value, but !var! returns the the run-time value, so in this case, filename has each value of %%x appended to it as the loop proceeds. (Caution : there is a limit of ~8180 characters in a batch variable [actually, 8191-length of variablename])

Upvotes: 4

Related Questions