Create a file in every folder in a directory - python

I have a directory with hundreds of folders and subfolders and subfolders within subfolders (in windows).
I'm just trying to create a small txt file with the word "test" in all of these folders.
I've tried something like this but can't get it to work properly:
for i in root_dir:
filename = "test.txt"
with open(filename, "w") as f:
f.write("Test")
attempt2
#only makes one file in the root directory - no sub directories though
import os
root_path8 = r'C:\Users\max\Downloads\users_visual\mgr8\mgr7\mgr6'
for i in next(os.walk(root_path8))[1]:
# print(j)
print(i)
root_dir = root_path8
filename = "test.txt"
filepath = os.path.join(root_dir, filename)
if not os.path.exists(root_dir):
os.makedirs(root_dir)
f = open(filepath, "a")
f.write("Test")
f.close()

Use walk to get all subfolders and sub-subfolders etc. within your directory. This iteration returns 3 values (current folder, subfolders, files); pass the first value to open, using os.path.join to concatenate the folder name and the file name. E.g.
import os
folder_iter = os.walk(root_dir)
for current_folder, _, _ in folder_iter:
filename = "test.txt"
with open(os.path.join(current_folder, filename), "w") as f:
f.write("Test")
BTW if it's the same file in every case, i.e. you don't need to CREATE each file separately, probably a more efficient way would be to create one file to begin with and then copy it to each folder in the iteration.

Related

Modify all PHP files within directory and subdirectories with Python

I'm having issues scanning through a root directory and modifying all .php files that contain a certain reference. Essentially, we're looking to move our entire database. I have to find all records of certain tables and rename them appropriately. Here's the code I have so far:
import os
import re
directory = 'C:/Users/me/Desktop/wsphp'
for root, dirs, files in os.walk(directory):
for filename in files:
if filename.endswith('.php'):
print(filename)
open_file = open(filename, 'r')
read_file = open_file.read()
regex = re.compile('OLD DATABASE NAME')
read_file = regex.sub('NEW DATABASE NAME', read_file)
write_file = open(filename, 'w')
write_file.write(read_file)
My code breaks when it attempts to open the file. The problem seems to be that 'filename' refers to JUST the filename without the entire directory ('index.php' rather than 'C:/Users/me/Desktop/wsphp/Subfolder/Subfolder2/index.php'). The root directory contains a few .php files as well as a bunch of subdirectories. Is there an easier way to go about this?
As you suspected, filename is just the filename. The path to the file is stored in root, so you need to do
open_file = open(os.path.join(root, filename), 'r')

Python change strings line by line in all files within a directory

So I have some files located in directory.
Some of the files contain paths like this and some are empty: C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module.c
What would be the best way to cut it just by counting backslashes from the end: So in this case we need to cut everything what is after 4th backslash when counting backward:
Folder1\Folder2\Folder3\Module.c
I need some function that will go through all files and do this on each line of a file.
Current code which do not work for some reason is:
directory = os.listdir(//path_to_dir//)
for file in directory:
with open (file) as f:
for s in f:
print('\\'.join(s.split('\\')[-4:]))
I would try something like this:
from pathlib import Path
def change(s):
return '\\'.join(s.split('\\')[-4:])
folder = Path.cwd() / "folder" # here is your folder with files
files = folder.glob("*")
for f in files:
with open(f, "r") as file:
content = file.read()
lines = content.split('\n')
new_lines = []
for line in lines:
new_lines.append(change(line))
with open(f, "w") as file:
file.write("\n".join(new_lines))
It look for all files in the subfolder folder, does replacing on every line of every file and saves the files.

How to open files in a directory starting from a specific file

In order to open all the files in a specific directory (path). I use the following code:
for filename in os.listdir(path): # For each file inside path
with open(path + filename, 'r') as xml_file:
#Do some stuff
However, I want to read the files in the directory starting from a specific position. For instance, if the directory contains the files f1.xml, f2.xml, f3.xml, ... ,f10.xml in this order, how can I read all the files starting from f3.xml (and ignore f1.xml and f2.xml) ?
Straightforward way
import os
keep = False
first = 'f3.xml'
for filename in os.listdir(path): # For each file inside path
keep = keep or filename == first
if keep:
with open(path + filename, 'r') as xml_file:
#Do some stuff

Python - Need to loop through directories looking for TXT files

I am a total Python Newb
I need to loop through a directory looking for .txt files, and then read and process them individually. I would like to set this up so that whatever directory the script is in is treated as the root of this action. For example if the script is in /bsepath/workDir, then it would loop over all of the files in workDir and its children.
What I have so far is:
#!/usr/bin/env python
import os
scrptPth = os.path.realpath(__file__)
for file in os.listdir(scrptPth)
with open(file) as f:
head,sub,auth = [f.readline().strip() for i in range(3)]
data=f.read()
#data.encode('utf-8')
pth = os.getcwd()
print head,sub,auth,data,pth
This code is giving me an invalid syntax error and I suspect that is because os.listdir does not like file paths in standard string format. Also I dont think that I am doing the looped action right. How do I reference a specific file in the looped action? Is it packaged as a variable?
Any help is appriciated
import os, fnmatch
def findFiles (path, filter):
for root, dirs, files in os.walk(path):
for file in fnmatch.filter(files, filter):
yield os.path.join(root, file)
Use it like this, and it will find all text files somewhere within the given path (recursively):
for textFile in findFiles(r'C:\Users\poke\Documents', '*.txt'):
print(textFile)
os.listdir expects a directory as input. So, to get the directory in which the script resides use:
scrptPth = os.path.dirname(os.path.realpath(__file__))
Also, os.listdir returns just the filenames, not the full path.
So open(file) will not work unless the current working directory happens to be the directory where the script resides. To fix this, use os.path.join:
import os
scrptPth = os.path.dirname(os.path.realpath(__file__))
for file in os.listdir(scrptPth):
with open(os.path.join(scrptPth, file)) as f:
Finally, if you want to recurse through subdirectories, use os.walk:
import os
scrptPth = os.path.dirname(os.path.realpath(__file__))
for root, dirs, files in os.walk(scrptPth):
for filename in files:
filename = os.path.join(root, filename)
with open(filename, 'r') as f:
head,sub,auth = [f.readline().strip() for i in range(3)]
data=f.read()
#data.encode('utf-8')

Python script for moving directories/files while ignoring certain directories/files using shutil?

I'm looking to build a python script that moves files/directories from one directory to another while referencing a list that notes the files to be copied over.
Here is what I have thus far:
import os, shutil
// Read in origin & destination from secrets.py Readlines() stores each line followed by a '/n' in a list
f = open('secrets.py', 'r')
paths = f.readlines()
// Strip out those /n
srcPath = paths[0].rstrip('\n')
destPath = paths[1].rstrip('\n')
// Close stream
f.close()
// Empty destPath
for root, dirs, files in os.walk(destPath, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
// Copy & move files into destination path
for srcDir, dirs, files in os.walk(srcPath):
destDir = srcDir.replace(srcPath, destPath)
if not os.path.exists(destDir):
os.mkdir(destDir)
for file in files:
srcFile = os.path.join(srcDir, file)
destFile = os.path.join(destDir, file)
if os.path.exists(destFile):
os.remove(destFile)
shutil.copy(srcFile, destDir)
The secrets.py files contains the src/dest paths.
Currently this transfers all files/directories over. I'd like to read in another file that allows you to specify which files to transfer (rather than making a "ignore" list).
You should read the file list
f = open('secrets.py', 'r')
paths = f.readlines()
f_list = open("filelist.txt", "r")
file_list = map(lambda x: x.rstrip('\n'), f_list.readlines())
....
....
and check before copying
for file in files:
if file in file_list# <--- this is the condition you need to add to your code
srcFile = os.path.join(srcDir, file)
....
if your file list contains pattern of file names to be copied try using "re" module of python to match your file name.

Categories

Resources