Search code examples
pythonpandastextdirectorymkdir

How to create Folder on the basis of files in a specific folder


I have a folder which comprises of several pdfs and word files.I want to create a new folder where I want subfolders on the basis of the files which I read earlier and each sub folder should have 3 blank text files lets say test1.txt,test2.txt,test.txt I am new to python kindly help....


Solution

  • from pathlib import Path
    
    files = Path().iterdir()
    
    for file in files:
        new_file_path = Path(f'./{file.stem}')
        new_file_path.mkdir(parents=True, exist_ok=True)
    
        for i in range(3):
            p = new_file_path / f'{i + 1}.txt'
            with p.open('w') as nf:
                 nf.write('')
    

    I run this script within directory, where I have one.doc, two.doc and three.pdf, for instance. After that I get next:

    one/
        1.txt
        2.txt
        3.txt
    two/
        1.txt
        2.txt
        3.txt
    three/
        1.txt
        2.txt
        3.txt
    one.doc
    two.doc
    three.pdf
    

    I hope, you are able to remove then unused files.