File Type Check करना
आप os.path.isfile Method का उपयोग करके Check कर सकते हैं कि कोई File Directory है या Regular File:
उदाहरण
>>> import os
>>> print(os.path.isfile('my_file.txt'))
True
>>> print(os.path.isfile('my_folder'))
False
Complete File Type Checking:
import os
def check_file_type(path):
if os.path.isfile(path):
return "Regular File"
elif os.path.isdir(path):
return "Directory"
elif os.path.islink(path):
return "Symbolic Link"
elif os.path.exists(path):
return "Other (Socket, FIFO, Device, etc.)"
else:
return "Does Not Exist"
# Test
print(check_file_type('my_file.txt')) # Regular File
print(check_file_type('my_folder')) # Directory
print(check_file_type('symlink')) # Symbolic Link
print(check_file_type('nonexistent')) # Does Not Exist
os.stat() का उपयोग करके Detailed Info:
import os
import stat
file_stat = os.stat('my_file.txt')
mode = file_stat.st_mode
if stat.S_ISREG(mode):
print("Regular File")
elif stat.S_ISDIR(mode):
print("Directory")
elif stat.S_ISLNK(mode):
print("Symbolic Link")
Pathlib का उपयोग (Python 3.4+):
from pathlib import Path
p = Path('my_file.txt')
print(p.is_file()) # True/False
print(p.is_dir()) # True/False
print(p.is_symlink()) # True/False
print(p.exists()) # True/False