6, అక్టోబర్ 2025, సోమవారం

Python program to Check if a File Exists or not.............program 48/50.........

To print the content of a file in Python only if it exists, you can combine a file existence check with file reading operations.
Here's how to achieve this using the os.path.exists() function and a with statement for file handling:
Python
import osfile_path = "your_file_name.txt"  # Replace with the actual file pathif os.path.exists(file_path):    # The file exists, now open and print its content    try:        with open(file_path, 'r') as file:            content = file.read()            print(f"Content of '{file_path}':")            print(content)    except Exception as e:        print(f"An error occurred while reading the file: {e}")else:    print(f"The file '{file_path}' does not exist.")
Explanation:
  • import os
    This line imports the os module, which provides functions for interacting with the operating system, including file system operations.
  • file_path = "your_file_name.txt"
    This variable stores the path to the file you want to check and potentially print. Remember to replace "your_file_name.txt" with the actual name and path of your file.
  • if os.path.exists(file_path):
    This is the core of the existence check. os.path.exists() returns True if the specified file_path refers to an existing file or directory, and False otherwise.
  • with open(file_path, 'r') as file:
    If the file exists, this block opens the file in read mode ('r'). The with statement ensures that the file is automatically closed even if errors occur.
  • content = file.read()
    This reads the entire content of the file and stores it in the content variable.
  • print(f"Content of '{file_path}':") 
    and print(content): These lines print a header and then the actual content of the file.
  • except Exception as e:
    This try-except block is included for robust error handling during file reading, in case issues like permission errors arise even if the file exists.
  • else:
    If os.path.exists() returns False, this block is executed, indicating that the file was not found.
  • .................................Using os.path.exists()

This method is part of the os module and returns True if the specified file exists; otherwise, it is False.

import os
# Python Check if file exists
if os.path.exists('filename.txt'):
    print("File exists")
else:
    print("File does not exist")

కామెంట్‌లు లేవు:

కామెంట్‌ను పోస్ట్ చేయండి