Home » Python

Python | print the file content along with the filename

In this tutorial, we are going to learn how to print the content of a text file along with the filename in python?
Submitted by Pankaj Singh, on December 30, 2018

Printing file name

To print the filename, we use "file_object.name".

Printing file's content

To print the content of a file, we use "read()" method with the "file_object", it returns the all content of a file.


In this example, there is a file named "data.txt", it contains the text "Hello world, how are you?" Here, we are printing its content and the filename.

def main():
	# opening the file
	fo = open("data.txt","r")
	# reading & printing the name
	print("Name of the File : ",fo.name)
	print("Content of File  :")
	# reading content of the file 
	str = fo.read()
	# printing content of the file
	# closing the file
if __name__=="__main__":main()


Name of the File :  data.txt
Content of File  :
Hello world, how are you?

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.