Python/File System: Difference between revisions

From Fundamental Ramen
Jump to navigation Jump to search
No edit summary
No edit summary
 
(22 intermediate revisions by the same user not shown)
Line 4: Line 4:
| Read/Write file mtime ||
| Read/Write file mtime ||
<source lang="python">
<source lang="python">
import os
import os.path
import os.path


mtime = os.path.getmtime('filename')
mtime = os.path.getmtime('filename')
os.utime('filename', (mtime, atime))
</source>
</source>
|-
|-
| Copy/Move file ||
| Copy/Move/Delete file ||
<source lang="python">
<source lang="python">
import os
import shutil
import shutil


shutil.copy(src, dst)
shutil.copy(src, dst)
shutil.move(src, dst)
shutil.move(src, dst)
shutil.rmtree(dir)
os.rename(src, dst)
os.remove(dst)
</source>
</source>
|-
|-
Line 25: Line 31:
</source>
</source>
|-
|-
| List directory ||
| Make/Delete directories. ||
<source lang="python">
<source lang="python">
import os
import os.path
import os.path


items = os.path.listdir()
os.path.mkdir('dirname')          # Standard
for i in items:
if not os.path.isdir('dirname'):
    os.makedirs('dirname')  # Recursively
os.rmdir('dirname')              # Only works for empty directory.
os.removedirs('dirname')          # Recursively
</source>
|-
| Change/List directory ||
<source lang="python">
import os
 
os.chdir('sucks')
 
for i in os.listdir():
     print(i)
     print(i)
</source>
|-
| Relative path from source path<br>See: [https://stackoverflow.com/questions/7116889/python-file-attribute-absolute-or-relative StackOverFlow 1] [https://stackoverflow.com/questions/38412495/difference-between-os-path-dirnameos-path-abspath-file-and-os-path-dirnam/38412504 StackOverFlow 2] ||
<source lang="python3">
from os.path import abspath, dirname
abspath(abspath(dirname(__file__)) + '/../../data')
</source>
</source>
|}
|}

Latest revision as of 02:59, 28 August 2019

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.makedirs('dirname')   # Recursively
os.rmdir('dirname')               # Only works for empty directory.
os.removedirs('dirname')          # Recursively
Change/List directory
import os

os.chdir('sucks')

for i in os.listdir():
    print(i)
Relative path from source path
See: StackOverFlow 1 StackOverFlow 2
from os.path import abspath, dirname

abspath(abspath(dirname(__file__)) + '/../../data')