-1

How do I index a path with a counter (syntax it means) in Python? For example, I have this code:

while i<5:
    with open("xxx\\xxx\\test(i)","r+") as f:
        f.write("hello")

The output should be on 5 files: test0, test1, test2, test3, test4.

Ollie
  • 1,641
  • 1
  • 13
  • 31
Itachi
  • 21
  • 6

2 Answers2

0

Use .format() to add the index to your filename. Also remember to include the initialization and incrementation of i, and open the file with write access.

i = 0
while i<5:
    with open("xxx\\xxx\\test({})".format(i), "w+") as f:
        f.write("hello")
    i += 1
Ollie
  • 1,641
  • 1
  • 13
  • 31
0
from itertools import count
for i in count(0):
    if i >= 5:break
    with open(r"test {0}".format(str(i)), "w") as file:
        file.write("Hello World")
Rachit kapadia
  • 705
  • 7
  • 18