Working with Files and Paths in Python - Python class
Working with Files and Paths in Python
Importing Required Modules
Python provides the os
module to work with file system paths. To use its path-related functions, import os.path
:
import os.path
print(dir(os.path))
Some useful functions from os.path
:
exists(path)
: Checks if a given path exists.abspath(path)
: Returns the absolute path of a given file or directory.basename(path)
: Returns the base name of the given file or directory.isdir(path)
: Checks if the given path is a directory.isfile(path)
: Checks if the given path is a file.islink(path)
: Checks if the given path is a symbolic link.realpath(path)
: Returns the canonical path of the specified filename.
Checking If a Path Exists and Its Type
The following code checks whether a given path exists and determines if it is a file or directory:
import os
path = "F:\\b45\\book1.xlsx"
if os.path.exists(path):
if os.path.isdir(path):
print("It is a directory")
elif os.path.isfile(path):
print("It is a file")
elif os.path.islink(path):
print("It is a link")
else:
print("Path does not exist")
Checking another path:
path1 = "f:\\dir1"
if os.path.exists(path1):
print("It is a directory")
else:
print("Path does not exist")
Working with file paths:
path = "file.txt"
if os.path.exists(path):
print(os.path.abspath(path))
print(os.path.realpath(path))
print(os.path.basename(path))
Checking Path Existence and Counting Files in a Directory
import os
def check(path):
if os.path.exists(path):
if os.path.isdir(path):
dir_list = os.listdir(path)
return len(dir_list)
if os.path.isfile(path):
return os.path.basename(path)
dirp = "F:\\People\\durgareddy\\dir1"
Listing Python Files in a Directory
for root, dirs, files in os.walk("d:/ee"):
for file in files:
if file.endswith(".py"):
print("Python file:", file)
File Handling in Python
To handle files in Python, we can:
- Open and close files
- Read, write, and append data
File Access Modes
- Read:
'r'
- Write:
'w'
- Append:
'a'
Opening a File
filename = "file.txt"
file = open(filename, "r")
filecontent = file.read()
print(filecontent)
print(type(filecontent))
print(filecontent.count("error"))
This script reads the content of file.txt
, prints its content, data type, and counts occurrences of the word "error" in the file.