-2

Here is a code that randomly writes to a file with filename random1.txt, random2.txt n so on based on the number of files given by the user. I'm using pathlib to create directories. I want to move these files to each of the directories when I run the script. For ex - When the user gives input 2 for "Enter the number of iterations needed" prompt The script should generate Sample1 folder and random1.txt should be inside Sample1 folder and Sample2 folder should have random2.txt

import os, glob, shutil
import random, getpass
from pathlib import Path
def sample() -> None:
    username = getpass.getuser()
    number_of_iteration = int(input("Enter the number of iterations needed\n"))
    for i in range(1, number_of_iteration + 1):
        file_name = f"randomfile{i}" + '.txt'
        with open('C:/Users/{0}/PycharmProjects/SampleProject/{1}'.format(username, file_name), 'w') as f:
            list_of_something = [something1, something2, something3]
            random_generator_of_something = random.choice(list_of_something)
            for key, value in random_generator_of_something.items():
                        #does something
                    #writes something to the random file.txt
        with open('C:/Users/{0}/PycharmProjects/SampleProject/{1}'.format(username, file_name), 'a') as f:
                    #writes something to the random file.txt
        Path("C:/Users/{0}/PycharmProjects/SampleProject/Sample{1}".format(username, i)).mkdir(parents=True,
                                                                                                         exist_ok=True)

something1 = {
    'a' : 'b'
}

something2 = {
    'c' : 'd'
}

something3 = {
    'x' : 'y'
}```

1 Answers1

-1

You can try runing this code after your code. This will create folder for every text file and move into it

import glob, os
import shutil

folder = r"C:\Users\****\***\SampleProject" #Project folder change this according to your location

for file_path in glob.glob(os.path.join(folder, '*.*')):
    new_dir = file_path.rsplit('.', 1)[0]
    os.mkdir(os.path.join(folder, new_dir))
    shutil.move(file_path, os.path.join(new_dir, os.path.basename(file_path)))

You will get something like

enter image description here

  • When Im assigning the `folder = 'C:/Users/{0}/PycharmProjects/SampleProject'.format(username)` its generating a folder for each randomfile that's working perfectly fine but its also making a folder to the file in which I'm writing this code and its also making directories to other .py files. I just wanted the code to create Random1 directory inside C:/Users/{0}/PycharmProjects/SampleProject and put that random1.txt file into it and so on.. – abhishekravoor May 22 '23 at 13:01