docs
  • Overview
  • 🐍 PYTHON
    • Type Hints
    • PEP8 Style Guide for Python Code
    • 🏡Pipenv
    • Pathlib
  • 🕸Django
    • 🗄models
      • 🎯Best Practices
      • 🚦Django Signals
    • ⚙️ settings
    • DRF
      • Serializer
      • Authentication
      • Permissions
      • Viewsets
    • Testing
      • Faker and Factory Boy
    • 🧪Test Coverage
    • 💦Python-Decouple
    • Django Tips:
    • 💾Django ORM Queryset
    • Custom Exceptions
    • Celery
    • Resources
  • Deploy
    • 🚀Django Deployment
    • 🔒Setup SSL Certificate
  • 💾Database
    • MongoDB
  • 🛠️DevOps
    • 🖥Scripting
      • A First Script
      • Loops
      • Test
      • Variables
      • External programs
      • Functions
    • Command Line Shortcuts
    • Basic Linux Commands
    • 🎛Microservices
    • 🐳Docker
      • Docker Commands
      • Docker Compose
      • Django project
    • Kubernates
  • 📝Software IDE
    • EditorConfig
    • Linters
    • VsCode
Powered by GitBook
On this page
  • Show Current Directory
  • Check Directory of File Existing
  • OS Library
  • Pathlib
  • Create a Directory
  • Creating a path by passing folder and filename
  • Relative path to another path
  • Comparing two paths
  • Join Path
  • File or directory
  • Moving files with pathlib
  • Copy file
  • Path touch
  • Show Directory Content
  • Quick Read/Write to File
  • Metadata of the File
  • Converting a relative path to an absolute path

Was this helpful?

  1. PYTHON

Pathlib

File and directory access

The OS library in python which handles almost all the basic file system operations. Now the Pathlib , which is a built-in python library. it is intuitive in terms of syntax, easier to use, and has more features out of the box. Paths are not strings.

Show Current Directory

from pathlib import Path

# Current Working Directory
Path.cwd()


# User Home Directory
home_dir = Path.home()

# Relative path to the current folder
p = Path()  # PosixPath('.')


# Parent of path

p.parent
import os

os.getcwd()

The OS library will return a string, whereas the Pathlib will return an object of PosixPath.

Component of Path

  • .name: the file name without any directory

  • .parent: the directory containing the file, or the parent directory if path is a directory

  • .stem: the file name without the suffix

  • .suffix: the file extension

  • .anchor: the part of the path before the directories

Check Directory of File Existing

OS Library

The function os.path.exists(str_path) takes a string type argument, which can be either the name of a directory or a file.

import os

os.path.exists('/use/Username/Desktop/try.python')

Pathlib

When using the Pathlib, we simply pass the path as a string to the "Path" class, which will give us a "PosixPath" object.

from pathlib import Path

Path('some_path/README.md').exists()

Create a Directory

from pathlib import Path

Path('test_dir').mkdir()

# check if file exist 
Path('test_dir').mkdir(exist_ok=True)
import os

os.mkdir('test_dir') 
# if directory exists it will raise FileExistsError

if not os.path.exists('test_dir'):
    os.mkdir('test_dir')

The function mkdir() accepts a flag exist_ok . When it is set to true, the FileExistsError error is automatically ignored. When its parent directories are not existing. we just need to set the flag parents to true.

Creating a path by passing folder and filename

p = Path('folder_name', 'filename.json')

Relative path to another path

p1 = Path('folder1', 'filename.txt')

p2 = Path('folder1')

p_relative = p1.relative_to(p2)

p_relative
# PosixPath('filename.txt')

Comparing two paths

p1 = Path('folder1', 'filename.txt')

p2 = p1.resolve()

p1.samefile(p2)

Join Path

from pathlib import Path

Path.home() / 'python' / 'scrupts' / 'test.py'

# OR

Path.home().joinpath('python', 'scripts', 'tests.py')

File or directory

p1.is_dir()

p1.is_file()

Moving files with pathlib

from pathlib import Path

path = Path('names.txt')

path.rename('mynames.txt')


p = Path('folder1', 'file1.json')

# Move file1 into folder2 and rename it as file-1

p.rename(Path('folder2', 'file-1.json'))

Copy file

from pathlib import Path
from shutil import copyfile

source = Path('words.txt')
destination = Path('words_bck.txt')

copyfile(source, destination)

Path touch

from pathlib import Path

Path('myfile.txt').touch()

Show Directory Content

When we want to show the content of a directory.

Path('sample_data').iterdir()

The OS library doesn't provide the feature to search files using wildcards. Therefore, we have to import another library called Glob to help.

from glob import glob

list(glob(os.path.join('sample_data', '*.csv')))
from pathlib import Path

list(Path('sample_data').glob('*.csv'))

Quick Read/Write to File

path = Path.cwd() / 'README.md'

with open(path, mode='r') as f:
    print(f.read())

# OR

with path.open(mode='r') as f:
    print(f.read())


f = Path('test_dit/test.txt')
f.read_text()
f.write_text('This is a first line')

Metadata of the File

Converting a relative path to an absolute path

# Absolute path of a file

p.resolve()
# Get filename without extension

f.stem

# Get file extension

f.suffix

# Get statistics, create/update time

f.stat()

# Get the size of the file.

f.stat().st_size

Previous🏡PipenvNext🗄models

Last updated 3 years ago

Was this helpful?

🐍