Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> Python

Python में Check करें कि File Directory है या Regular File?


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

  1. - पायथन में वर्तमान फ़ाइल की डायरेक्टरी का फुल पथ कैसे प्राप्त करें?

    वर्तमान फ़ाइल का पूरा पथ जानने के लिए os मॉड्यूल का उपयोग करें। उदाहरण >>> import os >>> print(os.path.realpath(__file__)) /home/ayush/qna/path.py

  1. - पायथन में cd कैसे करें?

    आप os मॉड्यूल का उपयोग करके पायथन में डायरेक्टरी बदल सकते हैं या cd कर सकते हैं। यह उस डायरेक्टरी के रिलेटिव/एब्सोल्यूट पथ को इनपुट के रूप में लेता है जिस पर आप स्विच करना चाहते हैं। उदाहरण >>> import os >>> os.chdir(my_folder)

  1. - Java में फाइल या डायरेक्टरी के अस्तित्व को सत्यापित करें: चरण-दर-चरण गाइड

    Java में, फाइल या डायरेक्टरी मौजूद है या नहीं यह जांचने के दो प्राथमिक तरीके हैं। ये हैं: 1 - NIO पैकेज से Files.exists 2 - लिगेसी IO पैकेज से File.exists आइए प्रत्येक पैकेज के कुछ उदाहरण देखें। फाइल मौजूद है या नहीं जांचें (Java NIO) कोड Java NIO पैकेज से Path और Paths का उपयोग करके जांचता है