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.

Example:

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
	print(str)
	# closing the file
	fo.close()
if __name__=="__main__":main()

Output

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




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.