Get full path of argument [duplicate] - python

This question already has answers here:
How do I check whether a file exists without exceptions?
(40 answers)
Closed 6 years ago.
How can I code a Python script that accepts a file as an argument and prints its full path?
E.g.
~/.bin/python$ ls
./ ../ fileFinder.py test.md
~/.bin/python$ py fileFinder.py test.md
/Users/theonlygusti/.bin/python/test.md
~/.bin/python$ py fileFinder.py /Users/theonlygusti/Documents/Online/theonlygusti.github.io/index.html
/Users/theonlygusti/Documents/Online/theonlygusti.github.io/index.html
So, it should find the absolute path of relative files, test.md, and also absolute path of files given via an absolute path /Users/theonlygusti/Downloads/example.txt.
How can I make a script like above?

Ok, I found an answer:
import os
import sys
relative_path = sys.argv[1]
if os.path.exists(relative_path):
print(os.path.abspath(relative_path))
else:
print("Cannot find " + relative_path)
exit(1)

Related

delete images containing specific word in its name using python [duplicate]

This question already has answers here:
How do i search directories and find files that match regex?
(4 answers)
Closed 8 months ago.
In the directory there are multiple images with names:
I want to delete all images with "340" in it using a python code.
Assuming that the images are in desktop/images/
I'm not sure why you need to use Python and can't just use your shell (in bash it would just be rm desktop/images/*340*)
But in Python I think the shortest way would be
import os, glob
for file in glob.glob("desktop/images/*340*"):
os.remove(file)
or even:
import os, glob
[os.remove(file) for file in glob.glob("desktop/images/*340*")]
You can use this example, you'll have to adjust the code for your correct directory:
import os
import re
for file in os.listdir("Desktop/Images"):
if re.search("340.*?\.jpg$", file):
os.remove("Desktop/Images/" + file)
print("Deleted " + file)
else:
print("No match for " + file)

check whether a file is in Desktop folder or not Python [duplicate]

This question already has answers here:
How do I check whether a file exists without exceptions?
(40 answers)
Closed 1 year ago.
I am using os.getcwd() to get user current directory. I want to check whether a file is in Desktop folder or not. But getcwd() function only returns
username directory, like this /Users/macbookair, but I expect this:
/Users/macbookair/Desktop
I am using macOS Big Sur. Any help would be greatly appreciated. THanks
You can use os.chdir('/Users/macbookair/Desktop') to change directory and
os.listdir() - to list the file names in that directory.
import os #os module is helpful in interacting with os using python*
os.chdir("C:/Users/user/Desktop") #change directory to desired path
print(os.listdir()) #list of files at desired path
filename = str(input()) #typing name of file to check
if filename in os.listdir():
print(True) #if filename exists
else:
print(False) #if filename doesnot exists

An existing file not being identified using os.path.isfile function [duplicate]

This question already has answers here:
os.makedirs doesn't understand "~" in my path
(3 answers)
Closed 6 months ago.
I have a file 7.csv in directory: '~/Documents/Jane/analyst/test/1/'. I was able to read this file using pandas.read_csv function with no problem.
f_path = '~/Documents/Jane/analyst/test/1/7.csv'
pd.read_csv(f_path, index_col=None, header=0)
But when checking whether this file is exsiting using os.path.isfile(), the result return False.
os.path.isfile(f_path)
False
What could be the the possible error source?
Both os.path.isfile() and os.path.exists() do not recognize ~ as the home directory. ~ is a shell variable not recognized in python. It has to be either fully specified or you can use relative directory name.
But if you want to use ~ as home, you can do
from os.path import expanduser
home = expanduser("~")
As hun mentioned, your code should be
import os
f_path = '~/Documents/Jane/analyst/test/1/7.csv'
os.path.isfile(os.path.expanduser(f_path))
This will expand the tilde into an absolute path. ~, . and .. do not have the same meaning to the python os package that they do in a unix shell and need to be interpreted by separate functions.

How to get the name of parent directory in Python? [duplicate]

This question already has answers here:
How do I get the parent directory in Python?
(21 answers)
Closed 7 years ago.
I have a program in python that prints out information about the file system... I need to know to save the name of the parent directory to a variable...
For example, if a tiny bit of the file system looked like this:
ParentDirectory
ChildDirectory
SubDirectory
If I was inside of ChildDirectory, I would need to save the name ParentDirectory to a certain string... here is some pseudo code:
import os
var = os.path.parent()
print var
On a side note, I am using Python 2.7.6, so I need to be compatible with 2.7.6...
You can get the complete file path for the script resides using __file__ variable , then you can use os.path.abspath() to get the absolute path of your file , and then use os.path.join() along with your current path , and the parent directory descriptor - .. in most operating systems , but you can use os.pardir (to get that from python , so that it is truly platform independent) and then again get its absolute path to get the complete path of current directory, then use it with same logic again to get its parent directory.
Example code -
import os,os.path
curfilePath = os.path.abspath(__file__)
# this will return current directory in which python file resides.
curDir = os.path.abspath(os.path.join(curfilePath, os.pardir))
# this will return parent directory.
parentDir = os.path.abspath(os.path.join(curDir, os.pardir))

How to output the running path instead of the location path? [duplicate]

This question already has answers here:
How can I know the path of the running script in Python?
(3 answers)
Closed 8 years ago.
I have the following:
% more a.py
import os
os.system('pwd')
% python a.py
/Users/yl/test/f
% cd ..
% python ./f/a.py
/Users/yl/test
Basically I want the last output to be "/Users/yl/test/f", which is the path where the script is located (not where python was invoked). Have played around but didn't find a good solution. Thanks for any suggestions!
import os
app_dir = os.path.dirname(__file__)
print(app_dir)
import os
print (os.path.dirname(os.path.abspath(__file__)))

Categories

Resources