Ask Your Question
1

What is the process of writing Python code to read a file and display its characteristics regarding type and size?

asked 2021-08-27 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-05-02 16:00:00 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-27 11:00:00 +0000

Seen: 7 times

Last updated: May 02 '22