I've got a .txt file set up like:
Data1
Data2
Data3
Data4
Data5
(etc.)
Is there any way for me to get the first line of data and set is as a variable in a .bat file, after which it performs a task, and moves on to the next line?
Eg. Data 1 being used for a task, after which Data 2 is loaded for that same task, continuing down the list.
If that's not (easily) possible in a .bat file (through .txt data), how else would I do this (in a Python file, for example)?
CodePudding user response:
In bat: for multiple variables:
@echo off
setlocal enabledelayedexpansion
set count=0
for /f "tokens=*" %%x in (textfile.txt) do (
set /a count =1
set var[!count!]=%%x
)
echo %var[4]%
pause >nul
print variable 4 - echo %var[4]%
read file cotects into a variable:
for /f "delims=" %%x in (file.txt) do set Var=%%x
echo %var%
or:
set /p Var=file.txt
echo %Var%
This code will read the entire file into memory and remove all whitespace characters (newlines and spaces) from the end of each line:
with open(filename) as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines]
This code will take each line and assign to different variable:
var1 = lines[0]
var2 = lines[1]
CodePudding user response:
Using python to create a .bat file seems like a huge workaround.
I would recommend rather using os.system and open
running the commands one by one using read.
with open(txtfile,'r') as f:
for line in f:
os.system(line)
This will execute your .txt file row by row.
If you would rather create a bat file you can do:
with open(txtfile,'r') as f:
with open(batfile,'w ') as bf:
for line in f:
bf.write("echo " line)
os.system(batfile)
You should probably consider exploring your options with subprocess
as well.
CodePudding user response:
You can do it like that in batch file :
@echo off
(
Set /p Var1=
Set /p Var2=
Set /p Var3=
Set /p Var4=
Set /p Var5=
)<test.txt
echo The variable has a value : "%Var1%"
echo The variable has a value : "%Var2%"
echo The variable has a value : "%Var3%"
echo The variable has a value : "%Var4%"
echo The variable has a value : "%Var5%"
pause