Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here are the steps to write Python code to read a file and display its characteristics regarding type and size:

  1. Import the OS module to access file-related functions
import os
  1. Define the path to the file you want to read
path = "/path/to/your/file"
  1. Use the OS module to check if the file exists and get its size
if os.path.exists(path):
  file_size = os.path.getsize(path)
  print("File size:", file_size, "bytes")
else:
  print("File not found")
  1. Use the OS module to get the file extension and determine its type
if os.path.isfile(path):
  file_extension = os.path.splitext(path)[1]
  print("File extension:", file_extension)

  if file_extension == ".txt":
    print("File type: Text file")
  elif file_extension in [".csv", ".xls", ".xlsx"]:
    print("File type: Spreadsheet")
  elif file_extension in [".jpg", ".png", ".gif"]:
    print("File type: Image")
  else:
    print("Unknown file type")
else:
  print("Path is not a file")
  1. Run the program and check the output to see the file's characteristics.

Note: Make sure to change the path variable to the actual file path in your system before running the program.