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

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__)))

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)

How do i change Root(or starting directory) in python [duplicate]

This question already has answers here:
Get relative path from comparing two absolute paths
(6 answers)
Closed 1 year ago.
When i use os.getcwd() , it gives me something like this :
'/home/xxx/PycharmProjects/pythonProject3'
I want change it to something like this :
PycharmProjects/pythonProject3
in another word I wanna my os.getcwd() starts from where I want.
how can I do it?
i tried os.chdir and os.path.abspath(os.curdir) and it does not work.
I am using python3 and ubuntu.
Can you tell us how did you try chdir? Please see example below to change you current working director and let me know that output it gives on your machine.
>>> import os
>>> os.getcwd()
'/home/lllrnr101'
>>> os.chdir('/etc/')
>>> os.getcwd()
'/etc'
>>>

pyspark - how to delete a local directory if it already exists [duplicate]

This question already has answers here:
How do I remove/delete a folder that is not empty?
(22 answers)
Closed 5 years ago.
i wish to delete a local directory if it already exists. below is my code:
import sys
import os
from pyspark import SparkContext
from pyspark import SparkConf
conf=SparkConf().setAppName('pyspark')
sc=SparkContext(conf=conf)
data=sc.textFile('file:///home/cloudera/Downloads/SAN_SALES_EXTRACT_TRANS_LEVEL_D0906.txt')
datamap=data.map(lambda x: ((str(x.split(',')[1]).strip(),int(x.split(",")[0])),float(x.split(",")[10])))
datagrouped=datamap.reduceByKey(lambda x,y: x+y)
if (os.path.exists("file:///home/cloudera/Downloads/store_perday_rev")):
os.remove("file:///home/cloudera/Downloads/store_perday_rev")
else:
datagrouped.sortByKey().saveAsTextFile("file:///home/cloudera/Downloads/store_perday_rev")
#for i in datagrouped.sortByKey().take(20):
# print(i)
It doesn't delete the directory. What am i doing wrong?
Try os.rmdir() instead.
os.remove() only works for a file path, not for a directory.
You can try these options .
import os
os.rmdir("C:/test/delete/pydelete")
i am able to remove the folder.If you have the data in this folder then you need to call.
shutil.rmtree()
are your trying to remove the directory or the file?
if you are trying to remove the directory please refer to the following link:
How do I remove/delete a folder that is not empty with Python?
Also refer to the python docs:
https://docs.python.org/2/library/os.html

Get full path of argument [duplicate]

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)

os.unlink multiple file in python [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Deleting files by type in Python on Windows
How can I delete all files with the extension ".txt" in a directory? I normally just do
import os
filepath = 'C:\directory\thefile.txt'
os.unlink(filepath)
Is there a command like os.unlink('C:\directory\*.txt') that would delete all .txt files? How can I do that?
Thanks!
#!/usr/bin/env python
import glob
import os
for i in glob.glob(u'*.txt'):
os.unlink (i)
should do the job.
Edit: You can also do it in "one line" using map operation:
#!/usr/bin/env python
import glob
import os
map(os.unlink, glob.glob(u'*.txt'))
Use the glob module to get a list of files matching the pattern and call unlink on all of them in a loop.
Iterate through all files in C:\directory\, check if the extension is .txt, unlink if yes.

Categories

Resources