Python/File System: Difference between revisions
< Python
Jump to navigation
Jump to search
No edit summary |
No edit summary |
||
| Line 53: | Line 53: | ||
| Relative path from source path || | | Relative path from source path || | ||
<source lang="python3"> | <source lang="python3"> | ||
# Solution 1 | # Solution 1 | ||
os.path | from os.path import realpath, dirname | ||
realpath(realpath(dirname(__file__)) + '/../../data') | |||
# Solution 2 | # Solution 2 | ||
import os.path | |||
SRC_PATH = os.path.dirname(__file__) | SRC_PATH = os.path.dirname(__file__) | ||
if SRC_PATH != '': | if SRC_PATH != '': | ||
Revision as of 03:10, 27 June 2018
| TODO | CODE |
|---|---|
| Read/Write file mtime |
import os
import os.path
mtime = os.path.getmtime('filename')
os.utime('filename', (mtime, atime))
|
| Copy/Move/Delete file |
import os
import shutil
shutil.copy(src, dst)
shutil.move(src, dst)
shutil.rmtree(dir)
os.rename(src, dst)
os.remove(dst)
|
| Path conversion |
import os.path
CODE_PATH = os.path.realpath(os.path.dirname(__file__)) + '/'
DATA_PATH = os.path.expanduser('~/osm-data/')
|
| Make/Delete directories. |
import os
import os.path
os.path.mkdir('dirname') # Standard
if not os.path.isdir('dirname'):
os.path.makedirs('dirname') # Recursively
os.rmdir('dirname') # Only works for empty directory.
os.removedirs('dirname') # Recursively
|
| List directory |
import os
for i in os.listdir():
print(i)
|
| Relative path from source path |
# Solution 1
from os.path import realpath, dirname
realpath(realpath(dirname(__file__)) + '/../../data')
# Solution 2
import os.path
SRC_PATH = os.path.dirname(__file__)
if SRC_PATH != '':
DATA_PATH = os.path.realpath(SRC_PATH + '/../../data')
else:
DATA_PATH = os.path.realpath('../../data')
|