get script directory name - Python [duplicate] - python

This question already has answers here:
How do you properly determine the current script directory?
(16 answers)
Closed 2 years ago.
I know I can use this to get the full file path
os.path.dirname(os.path.realpath(__file__))
But I want just the name of the folder, my scrip is in. SO if I have my_script.py and it is located at
/home/user/test/my_script.py
I want to return "test" How could I do this?
Thanks

import os
os.path.basename(os.path.dirname(os.path.realpath(__file__)))
Broken down:
currentFile = __file__ # May be 'my_script', or './my_script' or
# '/home/user/test/my_script.py' depending on exactly how
# the script was run/loaded.
realPath = os.path.realpath(currentFile) # /home/user/test/my_script.py
dirPath = os.path.dirname(realPath) # /home/user/test
dirName = os.path.basename(dirPath) # test

>>> import os
>>> os.getcwd()

Just write
import os
import os.path
print( os.path.basename(os.getcwd()) )
Hope this helps...

Related

Why can't see image path?

why this function return False although the image already exists in that path and I wrote its name correctly
import cv2
import os
print(os.path.isfile('../Project/mark-zuker.png'))
The program is probably run from another directory. If you have those statements in a script, try with the absolute path:
code_dir = os.path.dirname(os.path.realpath(__file__))
file_img = os.path.dirname(code_dir) + '/Project/mark-zuker.png'
print(file_img)
print(os.path.isfile(file_img))

pyqt: How can I just print the file name after selecting the file (python)? [duplicate]

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 2 years ago.
I have created FileDialog to browse file.
After choosing the file, I want to get the name of the file only! But I always get full path.. and this is my Code:
self.pushButton_2.clicked.connect(self.pushButton_2_handler)
def pushButton_2_handler (self):
self.open_dialog_box()
def open_dialog_box(self):
filename=QFileDialog.getOpenFileName()
print(filename[0])
You can use the pathlib module:
>>> from pathlib import Path
>>> path = Path("C:/users/foobar/desktop/file.txt")
>>> path.name
'file.txt'
>>> path.stem
'file'
>>> path.suffix
'.txt'
>>>
Well file paths go like blah\blah\blah\filename so all you need to do is loop back until you find a \ and use that.
for index in range(len(filename[0])-1, 0,-1):
if filename[0][index] == "\\":
filename[0] = filename[0][index+1:]
break
you could also split up the string by \ and use the last one like
filename[0] = filename[0].split("\\")[-1]
or use os
import os
filename[0] = os.path.basename(filename[0])

how to detect file if exist in python [duplicate]

This question already has answers here:
How do I check whether a file exists without exceptions?
(40 answers)
Closed 3 years ago.
how can i detect if a specifics files exist in directory ?
example:
i want to detect if (.txt) files exist in directory (dir)
i tried with this :
import os.path
from os import path
def main():
print ("file exist:"+str(path.exists('guru99.txt')))
print ("File exists:" + str(path.exists('career.guru99.txt')))
print ("directory exists:" + str(path.exists('myDirectory')))
if __name__== "__main__":
main()
but all this functions you must to insert the complete file name with format(.txt)
Thank you !
from glob import glob
files = glob('*.txt')
print(len(files)) # will return the number of .txt files in the dir
print(files) # will return all the .txt files in the dir
to check if a specific file exists:
import os
os.path.exists(path_to_file)
will return True if it exists, False if not
to check if ANY .txt files exist:
import glob
if glob.glob(path_to_files_'*.txt'):
print('exists')
else:
print('doesnt')

Python / ImportError: Import by filename is not supported [duplicate]

This question already has answers here:
How can I import a module dynamically given the full path?
(35 answers)
Closed 8 years ago.
I'm trying to import a python file to my application which is written in python.
I have the following code:
import os
from os.path import basename
class specificClass:
def dothing(self,path):
runcommand = __import__("/root/"+ os.path.splitext(os.path.basename(path))[0]+ "/" + os.path.splitext(os.path.basename(path))[0] +"/sa/update.py")
runcommand.main()
When I run it, it gives me the following error:
ImportError: Import by filename is not supported.
Instead of doing a import like __import__ you can say
import sys
sys.path.append(path) # this is where your python file exists
import update

how to check if a file is a directory or regular file in python? [duplicate]

This question already has answers here:
How to identify whether a file is normal file or directory
(7 answers)
Closed 3 years ago.
How do you check if a path is a directory or file in python?
os.path.isfile("bob.txt") # Does bob.txt exist? Is it a file, or a directory?
os.path.isdir("bob")
use os.path.isdir(path)
more info here http://docs.python.org/library/os.path.html
Many of the Python directory functions are in the os.path module.
import os
os.path.isdir(d)
An educational example from the stat documentation:
import os, sys
from stat import *
def walktree(top, callback):
'''recursively descend the directory tree rooted at top,
calling the callback function for each regular file'''
for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode):
# It's a directory, recurse into it
walktree(pathname, callback)
elif S_ISREG(mode):
# It's a file, call the callback function
callback(pathname)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname
def visitfile(file):
print 'visiting', file
if __name__ == '__main__':
walktree(sys.argv[1], visitfile)

Categories