# Open the file in read mode
with open('filename.txt', 'r') as fo:
# Print the file name
print(f'Filename is: {fo.name}')
# Read and print the contents of the file
content = fo.read()
print('File Content:')
print(content)
# Count and display the number of lines in the file
fo.seek(0) # Reset pointer to the beginning
lines = fo.readlines()
print(f'Total Lines: {len(lines)}')
code
Read and Display Filename from a Text File
This Python script demonstrates how to open and read a file, display its name, print its contents, and count the number of lines. It’s a practical example of file handling in Python, showcasing techniques to extract and analyze file data.
File handling
Open file
Read file
File name
Text file
Print filename