Gen-AI Developer Classroom notes 19/Mar/2025

Well known file formats

  • CSV and TSV
  • JSON
  • YAML

CSV

  • This is used for tabular data, where each column is seperated by comman
  • TSV (Tab separated)
  • CSV is widely adopted standard
    Preview

Writing CSV files and Reading CSV files in Python

  • Refer Here for python standard libary module csv

JSON

  • This is collection of key value pairs. This format is inspired from JavaScript Objects
  • Json look exactly the same as python dictionary representations
  • an example json file representing a student
{
    "name": "abc",
    "id": 110011,
    "mobile": "999999999",
    "address": {
        "flatno": "601-B",
        "building": "nilgiri",
        "city": "Hyderabad"
    },
    "courses": ["GenAI", "Cloud" ],
    "online": true
}

Writing Json files and Reading Json files in Python

  • Python has a standard library module called as json

YAML

  • This also reprsents key value pairs
  • yaml follows python indentation for lists and maps (dictionaries)
---
name: abc
id: 111011
mobile: "99999999"
online: True
address:
  flatno: 601-B
  building: nilgiri
  city: Hyderadbad
courses:
  - GenAI
  - Cloud

Writing YAML files and Reading YAML files in Python

  • Python standard library doesnot have yaml support we can use pypi package pyyaml
  • Refer Here for example

Exercise:

  • Make changes in the inventory to write to
    • json
    • yaml
  • if the inventory file does not exist, create one from code with empty items

Checking if file exists or not in Python

Here are several approaches to check if a file exists in Python:

1. Using os.path Module

The os.path module provides multiple methods to check file existence:

  • os.path.exists(path): Checks if a path exists (file or directory).
    python
    import os
    print(os.path.exists("file.txt")) # True if file or directory exists

  • os.path.isfile(path): Checks if the path is an existing file.
    python
    print(os.path.isfile("file.txt")) # True if it's a file

  • os.path.isdir(path): Checks if the path is an existing directory.
    python
    print(os.path.isdir("directory")) # True if it's a directory

2. Using pathlib Module

Introduced in Python 3.4, pathlib provides an object-oriented approach:

  • Path.exists(): Checks if a path exists (file or directory).
  • Path.is_file(): Checks if the path is a file.
  • Path.is_dir(): Checks if the path is a directory.

Example:

from pathlib import Path

file = Path("file.txt")
print(file.exists())    # True if file or directory exists
print(file.is_file())   # True if it's a file
print(file.is_dir())    # True if it's a directory

3. Using try-except Block

This follows the EAFP (Easier to Ask for Forgiveness than Permission) principle. Instead of checking, attempt to open the file and catch exceptions.

try:
    with open("file.txt") as f:
        pass  # File exists
except FileNotFoundError:
    print("File does not exist")

4. Using os.access()

This checks for access permissions using the os.access() method.

import os

print(os.access("file.txt", os.F_OK))  # True if file exists

Comparison of Methods

| Method | Checks For | Returns | Notes |
|————————-|————————–|———|—————————————-|
| os.path.exists() | File or directory | True/False | General-purpose check |
| os.path.isfile() | File only | True/False | Specific to files |
| pathlib.Path.exists() | File or directory | True/False | Object-oriented |
| Try-except block | File existence | – | Raises exception for non-existence |
| os.access() | File existence & access | True/False | Can check permissions too |

Choose the method that best suits your use case!

Citations:
[1] https://note.nkmk.me/en/python-os-exists-isfile-isdir/
[2] https://ioflood.com/blog/python-check-if-file-exists/
[3] https://www.freecodecamp.org/news/how-to-check-if-a-file-exists-in-python/
[4] https://www.python-engineer.com/posts/check-if-file-exists/
[5] https://www.simplilearn.com/tutorials/python-tutorial/python-check-if-file-exists
[6] https://linuxize.com/post/python-check-if-file-exists/

By continuous learner

enthusiastic technology learner

Leave a Reply

Discover more from Direct AI Powered By Quality Thought

Subscribe now to keep reading and get access to the full archive.

Continue reading