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.
Related
Something so simple is not working for me. I want to os.walk through my subdirectories and if there is a specific filename that equals to __main__.py I want to execute a command
The file I'm using is below, and so is my other attempt. I'm sure I'm blind or forgetting something, thought reaching out to StackOverflow might catch something I can't see
This file below is the one I'm using, and the one below it provides proof the file is there in a subdirectory.
file.py
import os
def a():
current_dir = os.getcwd()
# Scans all files in bot directory
for dirs in os.walk(current_dir):
for file in dirs:
# Checks if filename "__main__.py" is there
if file == '__main__.py':
print("Found __main__.py")
else:
pass
When I do this:
import os
def a():
current_dir = os.getcwd()
# Scans all files in bot directory
for dirs in os.walk(current_dir):
for file in dirs:
print (file)
It returns this: (You can see that main.py is in the file, but the script at the very top of this post cannot see it)
['justinbieber', 'daviddobrik']
['.DS_Store']
/Users/path/1/justinbieber
['__pycache__', 'output_path']
['auth.py', 'run.py', 'startup.py', '.DS_Store', 'downloader.py', 'organize.py', 'constants.py', '__init__.py', 'assembler.py', 'logger.py', 'pil.py', 'helpers.py', '__main__.py', 'dlfuncs.py', 'comments.py']
/Users/path/1/justinbieber/__pycache__
You probably want to use os.listdir
def a():
current_dir = os.getcwd()
# Scans all files in bot directory
for file in os.listdir(current_dir):
if file == "__main__.py":
print("Found __main__.py")
else:
pass
a()
using os.walk
def a():
current_dir = os.getcwd()
# Scans all files in bot directory
for dirs,subdirs,files in os.walk(current_dir):
for file in files:
# Checks if filename "__main__.py" is there
if file == '__main__.py':
print("Found __main__.py")
else:
pass
a()
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
I have made a file search program which search for the file. it is working fine with searching in current working directory and also inside one folder, however it does not work folder inside folder, I am not getting why? Can anyone please help?
My Code:
import os
files = []
def file_search(file, path=""):
if path == "":
path = os.getcwd()
for item in os.listdir(path):
if os.path.isdir(item):
path = os.path.realpath(item)
file_search(file, path)
elif item == file:
files.append(item)
return files
print(file_search("cool.txt"))
I think it will be simpler if you used glob library.
Example:
import glob
files = glob.glob('**/cool.txt', recursive=True)
I've something like this in my program:
A main script main.py inside a folder named 'OpenFileinaModule'. There's a folder called 'sub' inside it with a script called subScript.py and a file xlFile.xlsx, which is opened by subScript.py.
OpenFileinaModule/
main.py
sub/
__init__.py (empty)
subScript.py
xlFile.xlsx
Here is the code:
sub.Script.py:
import os, openpyxl
class Oop:
def __init__(self):
__file__='xlFile.xlsx'
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
print os.path.join(__location__, __file__)
self.wrkb = openpyxl.load_workbook(os.path.join(__location__,
__file__),read_only=True)
main.py:
import sub.subScript
objt=sub.subScript.Oop()
When I execute main.py, I get the error:
IOError: [Errno 2] No such file or directory: 'C:\\Users\\...\\OpenFileInaModule\\xlFile.xlsx'
It jumps the sub folder...
I've tried
__file__='sub/xlFile.xlsx'
But then the "sub" folder is duplicated:
IOError: [Errno 2] No such file or directory: 'C:\\Users\\...\\OpenFileInaModule\\sub\\sub/xlFile.xlsx'
How to open xlFile.xlsx with subScript.py from main.py?
you're overriding __file__ with __file='xlFile.xlsx', do you mean to do this?
I think you want something like
import os
fname = 'xlFile.xlsx'
this_file = os.path.abspath(__file__)
this_dir = os.path.dirname(this_file)
wanted_file = os.path.join(this_dir, fname)
I'd suggest always using the absolute path for a file, especially if you're on windows when a relative path might not make sense if the file is on a different drive (I actually have no idea what it would do if you asked it for a relative path between devices).
Please avoid using __file__ and __location__ to name your variables, these are more like builtin variables which might cause a confusion.
Note something here:
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
You have not included sub directory and the above joins only the CWD + os.path.dirname(__file__). This doesn't get you to the file. Please read the documentation of os.path.dirname: os.path.dirname(__file__) returns an empty string here.
def __init__(self):
file = 'xlFile.xlsx'
location = os.path.join('sub', file)
location = os.path.abspath(location) # absolute path to file
location = os.path.realpath(location) # rm symbolic links in path
self.wrkb = openpyxl.load_workbook(location)
I am trying to list all the files in the current folder and also files in the folders of the current folder.
This is what I have been upto:
import os
def sendFnF(dirList):
for file in dirList:
if os.path.isdir(file):
print 'Going in dir:',file
dirList1= os.listdir('./'+file)
# print 'files in list', dirList1
sendFnF(dirList1)
print 'backToPrevDirectory:'
else:
print 'file name is',file
filename= raw_input()
dirList= os.listdir('./'+filename)
sendFnF(dirList)
This code does get me into folders of the current directory. But when it comes to sub-folders; it treats them as files.
Any idea what I am doing wrong?
Thanks in advance,
Sarge.
Prepending ./ to a path does essentially nothing. Also, just because you call a function recursively with a directory path doesn't change the current directory, and thus the meaning of . in a file path.
Your basic approach is right, to go down a directory use os.path.join(). It'd be best to restructure your code so you listdir() at the start of sendFnF():
def sendFnF(directory):
for fname in os.listdir(directory):
# Add the current directory to the filename
fpath = os.path.join(directory, fname)
# You need to check the full path, not just the filename
if os.path.isdir(fpath):
sendFnF(fpath)
else:
# ...
# ...
sendFnf(filename)
That said, unless this is an exercise, you can just use os.walk()