How to run a python script trough a folder with subfolders? - python

I am ripping dvd's to my plex server, and the way i have done it is like this.
\Storage
\Movie Name (xxxx)
Movie.mkv
Bonus Scene.mkv
\Movie2 Name (xxxx)
Movie2.mkv
etc
And what i want to do with my python script is to rename each MKV file to the folder name. But instead of running the script in each folder, how do i run it across the main storage folder and make it enter each subfolder?
My script looks like this (the script requires the movie title to be 1.mkv, i made it like that so it leaves the bonus scenes alone)
import os
folder = "{cwd}\\".format(cwd = os.getcwd())
src = "{folder}".format(folder=folder)
extension = "mkv"
def renamer():
path = os.path.dirname(src)
folder = os.path.basename(path)
os.rename("{directory}\\{file}".format(directory=src, file="1.mkv"),
"{directory}\\{file}.{extension}".format(directory=src, file=folder, extension = extension))
def listDir():
for file in os.listdir(src):
if file.endswith(".{extension}".format(extension = extension)):
return file
def main():
renamer()
if __name__ == "__main__":
main()

you can use:
for (dirpath, dirnames, filenames) in os.walk(your_initial_directory):
from there you get 3 lists dirpath, dirnames, filenames that are in your_initial_directory

Related

Python script to rename a file to the folder name

I am making a python script to change the name of a file in a folder to the same name of the folder.
For example if a folder is called TestFolder and the txt file in the folder is called test, the script will make the file called TestFolder.txt.
But, how can make the script work outside of the directory it is located in?
Beneath is my code so far, i hope i explained it good enough.
import os
temp = os.path.dirname(os.path.realpath(__file__))
src = "{temp}\\".format(temp=temp)
def renamer():
path = os.path.dirname(src)
folder = os.path.basename(path)
os.rename("{directory}\\{file}".format(directory=src, file=listDir()),
"{directory}\\{file}.txt".format(directory=src, file=folder))
def listDir():
for file in os.listdir(src):
if file.endswith(".txt"):
return file
def main():
print("Hello World")
print(listDir())
renamer()
print(listDir())
if __name__ == "__main__":
main()
Your problem is that you went to some trouble to specify the script location as the renaming path:
temp = os.path.dirname(os.path.realpath(__file__))
src = "{temp}\\".format(temp=temp)
def renamer():
path = os.path.dirname(src)
folder = os.path.basename(path)
The solution is simple: if you don't want the script's location as the path/folder, then don't do that. Put what you want in its place. Use the cwd (current working directory) to rename in the execution location; otherwise, re-code your program to accept a folder name as input. Either of these is readily available through many examples on line.

Traversing Directories

I am trying to write a python program that takes an input directory, and prints out all the .txt files that are in the directory. However, if there is another folder inside that one, it must do the same thing using recursion.
My problem is that is only does the .txt files and does not traverse further into the directory.
import os
path = input("What directory would you like to search?: ")
def traverse(path):
files = os.listdir(path)
for i in files:
if os.path.isdir(i) == True:
traverse(i)
elif i.endswith('.txt'):
print(i)
traverse(path)
What is the problem?
It looks like the reason your code is failing is because the if os.path.isdir(i) == True line always fails, regardless of whether or not the file is the directory. This is because the files variable stores relative paths rather than absolute paths, which causes the check to fail.
If you want to do it using the recursion method you gave, your code can be changed as follows:
import os
path = input("What directory would you like to search?: ")
def traverse(path):
files = os.listdir(path)
files = (os.path.join(os.path.abspath(path), file) for file in files)
for i in files:
if os.path.isdir(i) == True:
traverse(i)
elif i.endswith('.txt'):
print(i)
traverse(path)
Here is a better way to do it using fnmatch (adapted to suit the rest of your code from Use a Glob() to find files recursively in Python?). It will recursively search all files in the supplied directory, and match those that end with
import fnmatch
import os
path = input("What directory would you like to search?: ")
def traverse(path):
matches = []
for root, dirnames, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, '*.txt'):
matches.append(os.path.join(root, filename))
print matches
traverse(path)
You are missing full path otherwise it's fine. see below
def traverse(path):
files = os.listdir(path)
for i in files:
if os.path.isdir(os.path.join(path,i)):
traverse(os.path.join(path,i))
elif i.endswith('.txt'):
print(os.path.join(path,i))

How to select specific filenames nested within several folders?

I have a working folder on "C:\Users\userName\Desktop\test" where my python test script is located. My idea was to import directory from another drive ("D:\mydir\mytests\Projects") to my current working directory:
import os
from os import getcwd
curdir=os.getcwd()
path = os.chdir(os.path.join(curdir,"D:\mydir\mytests\Projects"))
Under "Projects" directory there are several folders which my contain also subfolders (but not every). I am trieng to make some kind of a generic code that will iterate over "Projects" directory access every folder or subfolder if it exist and find specific files with ".proj" extension. Found files (".proj") should than be writen out in a form of a list (maybe) so i can run each of them one by one with a for loop. I tried to write down some code but not successfully. Any suggestion will be appreciated a lot.
proj_list = []
for dirpath, dirnames, files in os.walk(path):
for f in files:
dest_dir = glob.glob('*.proj')
fullpath = os.path.join(dirpath, f.dest_dir)
proj_list.append(fullpath)
def activate_approval(dialog):
dialog.activate_button('yes')
class OpenAllProjectsFromListAndRun(script.TestScript):
def test_run (self):
for project in fullpath:
with self.handle_dialog(activate_yes):
self.open_project(project)
'''nothing in particular'''
if __name__ == '__main__':
test = OpenAllProjectsFromListAndRun()
test.run()
PS: I'm using Python 2.7

os.listdir() shows nothing while it is not so

I am trying to sort my files for school automatically but when I try this:
import os, sys
path = "/Sorting for School/"
dirs = os.listdir(path)
#print all dirs
for file in dirs:
print file
Although there are two txt documents in dir but when I run this the output is:
[]
Thanks
The code is fine. You must be querying a wrong path.
/dir/ means a subdirectory named dir in the root directory (in UNIX) or in the root directory of the current drive (in Windows).
Your code is fine. The following should work too:
import os
path = "/Sorting for School/"
def handle_err(err):
print err
for root,dirs,files in os.walk(path,onerror=handle_err):
for name in files:
print(name)

Python program to traverse directories and read file information

I'm just getting started with Python but already have found it much more productive than Bash shell scripting.
I'm trying to write a Python script that will traverse every directory that branches from the directory I launch the script in, and for each file it encounters, load an instance of this class:
class FileInfo:
def __init__(self, filename, filepath):
self.filename = filename
self.filepath = filepath
The filepath attribute would be the full absolute path from root (/). Here's the pseudocode mockup for what I'd like the main program to do:
from (current directory):
for each file in this directory,
create an instance of FileInfo and load the file name and path
switch to a nested directory, or if there is none, back out of this directory
I've been reading about os.walk() and ok.path.walk(), but I'd like some advice about what the most straightforward way to implement this in Python would be. Thanks in advance.
I'd use os.walk doing the following:
def getInfos(currentDir):
infos = []
for root, dirs, files in os.walk(currentDir): # Walk directory tree
for f in files:
infos.append(FileInfo(f,root))
return infos
Try
info = []
for path, dirs, files in os.walk("."):
info.extend(FileInfo(filename, path) for filename in files)
or
info = [FileInfo(filename, path)
for path, dirs, files in os.walk(".")
for filename in files]
to get a list of one FileInfo instance per file.
Try it
import os
for item in os.walk(".", "*"):
print(item)

Categories