Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeatedly create files with counter in Python

Bascially what I want to do is writing a python script that creates files with a count-number in the filename, "file 1.txt" "file 2.txt" "file 3.txt" for example.

I have come this far:

import shutil, os, itertools


for i in itertools.count():
    file = open("FILE " + str(i) + ".txt", 'w+')
    print(i)
    time.sleep(1)

Basically what I can do is count, but the file creation is my problem. open() doesnt seem to work.How do i create these files and how can I choose the directorys to store the files?

like image 320
diatomym Avatar asked Jan 23 '26 14:01

diatomym


2 Answers

import shutil, os, itertools
import time

dirpath = 'c:\\usr\\'
for i in itertools.count():
    file = open(dirpath+"FILE " + str(i) + ".txt", 'w+')
    print(i)
    time.sleep(1)

This will work. And your code works fine. I just added the directory path

like image 57
backtrack Avatar answered Jan 25 '26 03:01

backtrack


If you work on Python 3.4+, try pathlib.Path(...).touch,

import os
from pathlib import Path
import itertools

for i in itertools.count():
    filename = ''.join(['FILE', str(i), '.txt'])
    Path(os.path.join(dir, filename).touch()

In Python2, I think using the with statement is better.

import os
import itertools

for i in itertools.count():
    filename = ''.join(['FILE', str(i), '.txt'])
    with open(os.path.join(dir, filename), 'w'):
        pass
like image 21
SparkAndShine Avatar answered Jan 25 '26 04:01

SparkAndShine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!