user17712360
user17712360

Reputation:

How to make a path where the files will be created in?

I made a program that would create new text files every second but how can I make a path when those text files would be created in? (Example: Desktop)

Here is my code:

from time import sleep
import string
import random

def getR():
p = ""
for _ in range(0, 10):
    p += random.choice(string.ascii_letters)
return p
getR()

n = input("Are you sure you want to start this program?. \n")
if n == "yes":
  if __name__ == "__main__":
    while True:
        f = open("{}.txt".format(getR()), "w+")
        f.close()
        sleep (1)
else:
  print("Closing the file...")

Upvotes: 2

Views: 64

Answers (2)

Tim Roberts
Tim Roberts

Reputation: 54698

This does what you ask, although why you want to create an infinite number of randomly named empty files on your desktop is beyond me.

import os
from time import sleep
import string
import random

def getR():
    return ''.join(random.choice(string.ascii_letters) for _ in range(10)


if __name__ == "__main__":
    desktop = os.environ['USERPROFILE'] + "/Desktop/"
    while True:
        f = open(desktop + "{}.txt".format(getR()), "w+")
        f.close()
        sleep (1)

Upvotes: 2

Pedro Maia
Pedro Maia

Reputation: 2722

To change the working directory use os.chdir:

import os

os.chdir(PATH)

Or you can specify the path directly on open:

file = os.path.join(PATH, FILENAME)
f = open(file, 'w+')

Upvotes: 1

Related Questions