Skip to content

Instantly share code, notes, and snippets.

@CEZERT
Last active December 15, 2021 21:06
Show Gist options
  • Save CEZERT/04bdd21453bce784d66d80e953e391c3 to your computer and use it in GitHub Desktop.
Save CEZERT/04bdd21453bce784d66d80e953e391c3 to your computer and use it in GitHub Desktop.
#with os
import os
os.makedirs('2018/10/05', mode=0o770)
#with pathlib
import pathlib
p = pathlib.Path('2018/10/05')
p.mkdir(parents=True)
![](https://cdn.cacher.io/attachments/u/3fx93fy4dqwj6/TxcMjBCx96DMZnape_vfab5KxD33TPAX/wuyqebwpy.png)
from pathlib import Path
p = Path('example_directory')
try:
p.mkdir()
except FileExistsError as exc:
print(exc)
from pathlib import Path
p = Path('example_directory')
p.mkdir(exist_ok=True)
from datetime import datetime
from os import scandir
def convert_date(timestamp):
d = datetime.utcfromtimestamp(timestamp)
formated_date = d.strftime('%d %b %Y')
return formated_date
def get_files():
dir_entries = scandir('my_directory/')
for entry in dir_entries:
if entry.is_file():
info = entry.stat()
print(f'{entry.name}\t Last Modified: {convert_date(info.st_mtime)}')
import os
# List all files in a directory using os.listdir
path = "C:/Users/Marc Yeranosyan/PycharmProjects/Working_With_Files"
for p in os.listdir(path):
if os.path.isfile(os.path.join(path, p)): # for folders isdir
print (p)
import os
# List all files in a directory using scandir()
path = "C:/Users/Marc Yeranosyan/PycharmProjects/Working_With_Files"
with os.scandir(path) as entries:
for p in entries:
if p.is_file(): # for folders isdir
print(entry.name)
from pathlib import Path
# List all files in a directory using pathlib module
directory = Path("C:/Users/Marc Yeranosyan/PycharmProjects/Working_With_Files")
for p in directory.iterdir():
if p.is_dir():
print(p)
entries = os.listdir('my_directory/')
for entry in entries:
print(entry)
from pathlib import Path
path = Path("C:/Users/Marc Yeranosyan/PycharmProjects/Working_With_Files")
for p in path.iterdir():
print(p)
import os
with os.scandir('my_directory/') as entries:
for entry in entries:
print(entry.name)
with open('data.txt', 'r') as f:
data = f.read()
with open('data.txt', 'w') as f:
data = 'some data to be written to the file'
f.write(data)
![](https://cdn.cacher.io/attachments/u/3fx93fy4dqwj6/NhbVl_mQfxCjgZvjarHj7M6-NBEeBxaY/smutuiwz5.png)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment