Reputation: 53
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
Upvotes: 0
Views: 1161
Reputation: 2468
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
Upvotes: 3
Reputation: 1740
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)
Upvotes: 0
Reputation: 91
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
Upvotes: 0