Python: Handling variables as text to include into directories

47 Views Asked by At

I came across a problem in my script. Let's say I have an if-loop and a variable that is constantly increased by 1, like this:

i=0
if __name__ == "__main__":
   try: 
      while True
         file.open('example>i<.txt', 'a')
         file.write('some text')
         i+=1

...

In the first step, I want the file to be named example0.txt, then example1.txt in the next run and so on.

How do I convert my control variable i into string/text to e.g. include it into a directory ?

Thanks in advance Steve

3

There are 3 best solutions below

0
On BEST ANSWER

You can use the .format method. So in your case it will be:

i=0
if __name__ == "__main__":
   try: 
      while True
         file.open('example{}.txt'.format(i), 'a')
         file.write('some text')
         i+=1
0
On

You just need to consutruct the string with the control variable value substituted in it.

i=0
if __name__ == "__main__":
   try: 
      while True
         file.open("example"+str(i)+".txt", "a")
         file.write('some text')
         i+=1
0
On

Python 3.6 introduces format strings.

> i = 0
> f'example{i}.txt'
example0.txt