How to workaround `exist_ok` missing on Python 2.7?

One way around it is using pathlib. It has a backport for Python 2 and its mkdir() function supports exist_ok. try: from pathlib import Path except ImportError: from pathlib2 import Path # python 2 backport Path(settings.STATIC_ROOT).mkdir(exist_ok=True) As the comment suggests, use parents=True for makedirs(). Path(settings.STATIC_ROOT).mkdir(exist_ok=True, parents=True)

Misunderstanding of python os.path.abspath

The problem is with your understanding of os.listdir() not os.path.abspath(). os.listdir() returns the names of each of the files in the directory. This will give you: img1.jpg img2.jpg … When you pass these to os.path.abspath(), they are seen as relative paths. This means it is relative to the directory from where you are executing your … Read more

Difference between os.path.dirname(os.path.abspath(__file__)) and os.path.dirname(__file__)

BASE_DIR is pointing to the parent directory of PROJECT_ROOT. You can re-write the two definitions as: PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(PROJECT_ROOT) because the os.path.dirname() function simply removes the last segment of a path. In the above, the __file__ name points to the filename of the current module, see the Python datamodel: __file__ is the … Read more

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test. path=”C:\\Users\\Username\\Path\\To\\File” with open(path, ‘w’) as f: f.write(data) Edit: Here is a way to do it relatively instead … Read more

Pathlib vs. os.path.join in Python

pathlib is the more modern way since Python 3.4. The documentation for pathlib says that “For low-level path manipulation on strings, you can also use the os.path module.” It doesn’t make much difference for joining paths, but other path commands are more convenient with pathlib compared to os.path. For example, to get the “stem” (filename … Read more

How can I convert os.path.getctime()?

I assume that by right time you mean converting timestamp to something with more meaning to humans. If that is the case then this should work: >>> from datetime import datetime >>> datetime.fromtimestamp(1382189138.4196026).strftime(‘%Y-%m-%d %H:%M:%S’) ‘2013-10-19 16:25:38’

Python os.path.join() on a list

The problem is, os.path.join doesn’t take a list as argument, it has to be separate arguments. To unpack the list into separate arguments required by join (and for the record: list was obtained from a string using split), use * – or the ‘splat’ operator, thus: >>> s = “c:/,home,foo,bar,some.txt”.split(“,”) >>> os.path.join(*s) ‘c:/home\\foo\\bar\\some.txt’

tech