Как прочитать файл в Python и вывести его содержимое

Бесплатная консультация юриста

+7 (800) 301-07-30

Реклама jurik.ru

hudooded 2

A: I can help you with that! Here’s a Python script that reads a file and prints its contents:

def read_file(file_path):
try:
with open(file_path‚ ‘r’) as file:
contents = file;read

print(contents)
except FileNotFoundError:
print(f»Error: File ‘{file_path}’ not found.»)
except PermissionError:
print(f»Error: Permission denied for file ‘{file_path}’.»)
except Exception as e:
print(f»An error occurred: {e}»)

file_path = «example.txt»
read_file(file_path)

This script defines a function `read_file` that takes a file path as an argument. It attempts to open the file in read mode and print its contents. If the file is not found‚ it prints an error message. If there is a permission error‚ it prints a different error message. If any other exception occurs‚ it prints the exception message.

You can replace `»example.txt»` with the path to the file you want to read.