File Paths

OS Module - Basic Paths

  1. import os
  2. # check if exists
  3. os.path.exists("file.txt")
  4. #ans: True or False
  5. #ans: check if file
  6. os.path.isfile("file.txt")
  7. #ans: True or False
  8. #ans: check if directory
  9. os.path.isdir("folder")
  10. #ans: True or False

OS Module - Path Info

  1. import os
  2. # file size
  3. os.path.getsize("file.txt")
  4. #ans: size in bytes
  5. #ans: absolute path
  6. os.path.abspath("file.txt")
  7. #ans: /full/path/to/file.txt

OS Module - Join Paths

  1. import os
  2. # join paths
  3. os.path.join("folder", "file.txt")
  4. #ans: folder/file.txt
  5. #ans: works across platforms

OS Module - Split Paths

  1. import os
  2. # directory name
  3. os.path.dirname("/path/to/file.txt")
  4. #ans: "/path/to"
  5. #ans: base name
  6. os.path.basename("/path/to/file.txt")
  7. #ans: "file.txt"
  8. #ans: split extension
  9. os.path.splitext("file.txt")
  10. #ans: ("file", ".txt")

Pathlib Module

  1. from pathlib import Path
  2. # create path object
  3. path = Path("file.txt")
  4. #ans: check exists
  5. path.exists()
  6. #ans: True or False
  7. #ans: read file
  8. content = path.read_text()

Pathlib - Path Parts

  1. from pathlib import Path
  2. path = Path("/folder/file.txt")
  3. # name
  4. path.name
  5. #ans: "file.txt"
  6. #ans: stem
  7. path.stem
  8. #ans: "file"
  9. #ans: suffix
  10. path.suffix
  11. #ans: ".txt"
  12. #ans: parent
  13. path.parent
  14. #ans: Path("/folder")

Exercises - Part 1

  1. import os
  2. # exists vs isfile?
  3. os.path.exists("folder")
  4. #ans: True
  5. os.path.isfile("folder")
  6. #ans: False

Exercises - Part 2

  1. import os
  2. # join paths?
  3. os.path.join("a", "b", "c")
  4. #ans: "a/b/c" (or "a\\b\\c" on Windows)

Exercises - Part 3

  1. import os
  2. # splitext?
  3. os.path.splitext("file.tar.gz")
  4. #ans: ("file.tar", ".gz")

Exercises - Part 4

  1. from pathlib import Path
  2. # path / operator?
  3. Path("folder") / "file.txt"
  4. #ans: Path("folder/file.txt")

Exercises - Part 5

  1. from pathlib import Path
  2. # suffix with no extension?
  3. Path("file").suffix
  4. #ans: ""

Exercises - Part 6

  1. import os
  2. # abspath on absolute?
  3. os.path.abspath("/a/b/c")
  4. #ans: "/a/b/c" (unchanged)

Exercises - Part 7

  1. from pathlib import Path
  2. # multiple suffixes?
  3. Path("file.tar.gz").suffixes
  4. #ans: [".tar", ".gz"]

Exercises - Part 8

  1. import os
  2. # basename of directory?
  3. os.path.basename("/path/to/")
  4. #ans: ""
  5. os.path.basename("/path/to")
  6. #ans: "to"

Exercises - Part 9

  1. from pathlib import Path
  2. # parent of parent?
  3. Path("/a/b/c").parent.parent
  4. #ans: Path("/a")

Exercises - Part 10

  1. import os
  2. # current directory?
  3. os.getcwd()
  4. #ans: returns current working directory

Google tag (gtag.js)