3

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?

4
  • Do you want to create empty files? Commented Dec 2, 2016 at 14:13
  • Possible duplicate of Creating files and directories via Python Commented Dec 2, 2016 at 14:14
  • 1
    Works on my machine. Python 3.3 You will have to navigate to the directory you want the files created in with os.chdir Commented Dec 2, 2016 at 14:14
  • You could try to close the file within the for loop. Commented Dec 2, 2016 at 14:20

3 Answers 3

3
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

Sign up to request clarification or add additional context in comments.

1 Comment

Damn I only needed a path... Thanks though!!
3

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

Comments

1
import os

number = 0
valid = False
while not valid:
    usrInput = raw_input("How much candy?: ")
    try:
        int(usrInput)
        valid = True
    except:
        print "NUMBER of candys!!"
        pass
 while number < int(usrInput):
    number +=1 
    createFile = open('P:/' + str(number) + '.txt', 'w+')
    createFile.write("whatever you want")
    createFile.close()

I hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.