Python : how to get path to a folder knowing folder name? - python

Knowing the name of my folder "folder_name",
how can i easily get in python (script not in the same folder) the absolute path "/home/user/../path/to/../folder_name" ?

import os
directory = os.path.dirname(__file__)
file_path = os.path.join(directory, './filename.extension')
print(file_path)

Related

I am trying to get all folders on my machine but it only gives relative path I want full path

*No one come in here and say use os.path.abspath() I tried, it literally doesn't do what I want it just gives everything the drive of the current directory which isn't what I want I want to have the real drive.
I am getting the full path without the drive
example:
\\FileHistory\\fun64\\RAMPAGE\\Data\\$OF\\6413
Its not specifying the drive.
Code:
import os
root_dir = '\\'
folders = []
for path, dirs, files in os.walk(root_dir):
for dir in dirs:
full_path = os.path.join(path, dir)
folders.append(full_path)
print(folders)
I want to Specify what drive the folder is on at the start
import os
import win32api
folders = []
for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]:
for path, dirs, files in os.walk(drive):
for dir in dirs:
full_path = os.path.join(path, dir)
folders.append(full_path)
print(folders)

os module (opening folder)

I want to open the folder with the os module, but I can not do it,
because the os module can not recognize space (" ").
This is my path: C:/Users/Administrator/Desktop/New folder
And this is the error: The system cannot find the file C:/Users/Administrator/Desktop/New.
As you can see, the system can not recognize the space between (New) and (folder) and can not open the correct directory.
What should I do?
This is my code:
path = filedialog.askdirectory()
def open_folder():
os.system(f"start {path}")
You can use quotes
path = filedialog.askdirectory()
def open_folder():
os.system(f"start \"{path}\"")

shutil.move() only works with existing folder?

I would like to use the shutil.move() function to move some files which match a certain pattern to a newly created(inside python script)folder, but it seems that this function only works with existing folders.
For example, I have 'a.txt', 'b.txt', 'c.txt' in folder '/test', and I would like to create a folder '/test/b' in my python script using os.join() and move all .txt files to folder '/test/b'
import os
import shutil
import glob
files = glob.glob('./*.txt') #assume that we in '/test'
for f in files:
shutil.move(f, './b') #assume that './b' already exists
#the above code works as expected, but the following not:
import os
import shutil
import glob
new_dir = 'b'
parent_dir = './'
path = os.path.join(parent_dir, new_dir)
files = glob.glob('./*.txt')
for f in files:
shutil.move(f, path)
#After that, I got only 'b' in '/test', and 'cd b' gives:
#[Errno 20] Not a directory: 'b'
Any suggestion is appreciated!
the problem is that when you create the destination path variable name:
path = os.path.join(parent_dir, new_dir)
the path doesn't exist. So shutil.move works, but not like you're expecting, rather like a standard mv command: it moves each file to the parent directory with the name "b", overwriting each older file, leaving only the last one (very dangerous, because risk of data loss)
Create the directory first if it doesn't exist:
path = os.path.join(parent_dir, new_dir)
if not os.path.exists(path):
os.mkdir(path)
now shutil.move will create files when moving to b because b is a directory.

How to use the current folder the program is in?

When I open a file, I have to specify the directory that it is in. Is there a way to specify using the current directory instead of writing out the path name? I'm using:
source = os.listdir("../mydirectory")
But the program will only work if it is placed in a directory called "mydirectory". I want the program to work in the directory it is in, no matter what the name is.
def copyfiles(servername):
source = os.listdir("../mydirectory") # directory where original configs are located
destination = '//' + servername + r'/c$/remotedir/' # destination server directory
for files in source:
if files.endswith("myfile.config"):
try:
os.makedirs(destination, exist_ok=True)
shutil.copy(files,destination)
except:
this is a pathlib version:
from pathlib import Path
HERE = Path(__file__).parent
source = list((HERE / "../mydirectory").iterdir())
if you prefer os.path:
import os.path
HERE = os.path.dirname(__file__)
source = os.listdir(os.path.join(HERE, "../mydirectory"))
note: this will often be different from the current working directory
os.getcwd() # or '.'
__file__ is the filename of your current python file. HERE is now the path of the directory where your python file lives.
'.' stands for the current directory.
try:
os.listdir('./')
or:
os.listdir(os.getcwd())

How to acess files in other directory

My path is /cygdrive/c/Users/MyAccount/MyBox/myDev/trunk
My python scripts are located in /cygdrive/c/Users/MyAccount/MyBox/myScript/delivery
I want to get list of all files in python script folder as follows:
script_dir = os.path.dirname(os.path.abspath(__file__))
print('script_dir %s' % script_dir)
for root, dirs, files in os.walk(script_dir):
for file_name in files:
print(file_name)
I can't get it work because my script_dir prints :
script_dir /cygdrive/c/Users/MyAccount/MyBox/myDev/trunk/myScript/delivery
How can I make it works?
Thanks

Categories

Resources