F.E. PPS Unit 4 Practical 1 solution

Practical 1: Program to Open a File and Print Its Attribute Values

Problem Statement

Write a Python program to open a file and print its attribute values (like name, mode, and whether it is closed or not).

Solution Code

				
					# Program to open a file and print its attribute values

# Open the file in read mode
file = open("your_file_path", "r") # the path of you file should be put here (sample file like sample.txt or sample.docx)

# Print the file attributes
print("File Name:", file.name)
print("File Mode:", file.mode)
print("Is the file closed?", file.closed)

# Close the file
file.close()


				
			

Output

  • The program opens a file called sample.txt and prints its attributes:
    • File name
    • File mode
    • Whether the file is closed

Example output:

				
					File Name: D:\python\Sample.docx
File Mode: r
Is the file closed? False
Process finished with exit code 0
				
			

Explanation

Below is the explanation of F.E. PPS Unit 4 Practical 1 solution where we have written Python program to open a file and print its attribute values. 

  1. Opening the File:
    • The open() function is used to open the file in read mode (“r”).
  2. Printing File Attributes:
    • file.name returns the name of the file.
    • file.mode returns the mode in which the file was opened (e.g., “r” for read).
    • file.closed returns whether the file is closed or not (it will be False as it is open).
  3. Closing the File:
    • The file.close() method is used to close the file after operations.

Key Concepts Learned

  • Opening Files:
    • Using open() to access files in different modes.
  • File Attributes:
    • Accessing file attributes like name, mode, and closed status using file.name, file.mode, and file.closed.
Tech Amplifier Final Logo