0

I'd like to create a text file (with contents inside) and have that file copies/created in every subdirectory (folder) on a specific drive, say D with Python. Preferably using pre-installed python libraries and not needing to pip install anything.

So the Python 3 script runs from drive C, creates a text file with text inside it and pastes that text file once in every folder on Drive D. I need this to work on Windows.

create("file.txt", contents "example text")
copy("file.txt" to "D:\*")

Example output

Copied file.txt to D:\
Copied file.txt to D:\folder example
Copied file.txt to D:\folder example\subfolder example
Copied file.txt to D:\another folder
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 3
    Have you tried anything yet? It'll encourage more good answers if you post what you've tried so far – wpercy Oct 31 '18 at 18:28
  • I'm not very fluent with python at all. I used to use command prompt and make batch files all the time and I'm trying to move over to Python because command prompt is very limited and I'm struggling. I've had a look around online and haven't found anything which is why I've asked here. I don't know where to start. – OverflowingStack Oct 31 '18 at 18:31
  • OverflowingStack: If you don't even know where to start, then in IMO it sounds like you need to spend some more time learning Python and what's available in the many libraries/modules that come with it—instead of asking for a private tutor here. – martineau Oct 31 '18 at 19:43

3 Answers3

3

You can use os.walk to get all directories. For example, try

import os
filename = "myfile.txt"
filetext = "mytext"
directories = os.walk("D:")
for directory in directories:
    with open(directory[0]+"\\"+filename, "w") as file:
        file.write(filetext)

This will write filetext in a file myfile.txt in every directory in D:.

Edit: You might want to add a try statement to this, if you don't have permissions to a certain directory

user8408080
  • 2,428
  • 1
  • 10
  • 19
0

It is called recursive directory traversal

https://stackoverflow.com/a/16974952/4088577

Hope this hint will help you.

This is the line that interests you.

print((len(path) - 1) * '---', os.path.basename(root))

If you want to learn more you could read

https://www.bogotobogo.com/python/python_traversing_directory_tree_recursively_os_walk.php

0

Like so using OS lib:

from os import listdir
from os.path import isfile

path = "/some/path"

for f in listdir(path):
    if not isfile(path):
        filepath = "{0:s}/dummy.txt".format(path)
        with open(filepath, 'w') as f:
            f.write('Hi there!')

or using glob:

import glob

path = '/some/path/*/'
paths = glob.glob(path)
filename = "dummy.txt"

for path in paths:
    filepath = "{0:s}{1:s}".format(path, filename)
    with open(filepath, 'w') as f: 
        f.write('Hi there!')

Please Note!: Second solluton will work under Linux OS only (because of glob)

Raoslaw Szamszur
  • 1,723
  • 12
  • 21