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

Time:12-19

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...")

CodePudding user response:

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)

CodePudding user response:

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 ')
  • Related