# Specify the path to your text file file_path = 'your_file.txt'
with open(file_path, 'r', encoding='utf-8') as file: # Read the content of the file content = file.read() # Print the content print(content)
The content of the text file will be printed out in the terminal.
file_path
: Replace 'your_file.txt'
with the path to the text file you want to read. If the file is in the same directory as your Python script, you only need to provide the file name. Otherwise, you'll need to specify the full path.
open(file_path, 'r', encoding='utf-8')
: This line opens the file in read mode ('r'
). The encoding='utf-8'
parameter is optional and specifies the encoding of the file. If your file uses a different encoding, you should adjust this accordingly.
file.read()
: This method reads the entire content of the file into a single string. There are other methods for reading files, such as readline()
which reads one line at a time, and readlines()
, which reads the entire file and returns a list of strings, with each string representing a line in the file.
print(content)
: Finally, this line prints the content of the file to the console.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.