Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 7 of 10 · File Handling & Context Managers
Interview question

How do you handle file paths in a cross-platform way using pathlib? pathlib से cross-platform तरीके से file paths कैसे handle करें?

Answer

pathlib.Path provides an object-oriented, cross-platform way to work with file paths, replacing manual string concatenation and the older os.path module for most use cases.

from pathlib import Path

# Creating paths - works correctly on Windows, Linux, macOS
p = Path('data') / 'files' / 'report.txt'
print(p)  # data/files/report.txt (or data\files\report.txt on Windows)

# Compare to error-prone manual string concatenation
# bad_path = 'data' + '/' + 'files' + '/' + 'report.txt'  # breaks on Windows

# Common Path operations
p = Path('data/report.txt')
print(p.name)        # report.txt
print(p.stem)         # report (without extension)
print(p.suffix)       # .txt
print(p.parent)       # data
print(p.exists())     # True/False
print(p.is_file())    # True/False
print(p.absolute())   # full absolute path

# Reading/writing directly without open()
content = p.read_text()      # reads entire file as string
p.write_text('New content')  # writes string to file

# Creating directories
Path('new_folder').mkdir(exist_ok=True)  # exist_ok avoids error if it already exists
Path('nested/folders/here').mkdir(parents=True, exist_ok=True)  # creates all levels

# Iterating files in a directory
for file in Path('.').glob('*.txt'):  # all .txt files in current dir
    print(file)

for file in Path('.').rglob('*.py'):  # recursive - all .py files in subdirectories too
    print(file)

# Combining with open() when needed for more control
with open(p, 'r') as f:
    data = f.read()

pathlib.Path file paths के साथ काम करने का object-oriented, cross-platform तरीका देता है, manual string concatenation और पुराने os.path module से बेहतर।

from pathlib import Path

# Paths बनाना - Windows, Linux, macOS सभी पर सही काम करता है
p = Path('data') / 'files' / 'report.txt'
print(p)

# Common Path operations
p = Path('data/report.txt')
print(p.name)        # report.txt
print(p.stem)         # report
print(p.suffix)       # .txt
print(p.parent)       # data
print(p.exists())     # True/False
print(p.is_file())    # True/False

# open() के बिना पढ़ना/लिखना
content = p.read_text()
p.write_text('New content')

# Directories बनाना
Path('new_folder').mkdir(exist_ok=True)
Path('nested/folders/here').mkdir(parents=True, exist_ok=True)

# Directory में files iterate करना
for file in Path('.').glob('*.txt'):
    print(file)

for file in Path('.').rglob('*.py'):  # recursive
    print(file)

Was this answer clear?