0

I've been doing some scripting where I need to access the os to name images (saving every subsequent zoom of the Mandelbrot set upon clicking) by counting all of the current files in the directory and then using %s to name them in the string after calling the below function and then adding an option to delete them all

I realize the below will always grab the absolute path of the file but assuming we're always in the same directory is there not a simplified version to grab the current working directory

def count_files(self):
 count = 0
 for files in os.listdir(os.path.abspath(__file__))):
 if files.endswith(someext):
 count += 1
 return count
def delete_files(self):
 for files in os.listdir(os.path.abspath(__file__))):
 if files.endswith(.someext):
 os.remove(files)
asked Mar 19, 2015 at 5:15

3 Answers 3

1

Since you're doing the .endswith thing, I think the glob module might be of some interest.

The following prints all files in the current working directory with the extension .py. Not only that, it returns only the filename, not the path, as you said you wanted:

import glob
for fn in glob.glob('*.py'): print(fn)

Output:

temp1.py
temp2.py
temp3.py
_clean.py

Edit: re-reading your question, I'm unsure of what you were really asking. If you wanted an easier way to get the current working directory than

os.path.abspath(__file__) 

Then yes, os.getcwd()

But os.getcwd() will change if you change the working directory in your script (e.g. via os.chdir(), whereas your method will not.

answered Mar 19, 2015 at 5:18
Sign up to request clarification or add additional context in comments.

1 Comment

Yes that's what's i was looking for sorry if that was unclear.
0

Using antipathy* it gets a little easier:

from antipathy import Path
def count_files(pattern):
 return len(Path(__file__).glob(pattern))
def deletet_files(pattern):
 Path(__file__).unlink(pattern)

*Disclosure: I'm the author of antipathy.

answered Mar 19, 2015 at 6:02

Comments

0

You can use os.path.dirname(path) to get the parent directory of the thing path points to.

def count_files(self):
 count = 0
 for files in os.listdir(os.path.dirname(os.path.abspath(__file__)))):
 if files.endswith(someext):
 count += 1
 return count
answered Mar 19, 2015 at 6:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.