How to read a file and display the contents with Python.

Posted: May 14, 2014. At: 10:36 AM. This was 3 years ago. Post ID: 7202

How to read a file and display the contents with Python. This sample code reads and outputs the contents of a file using Python. This is a very simple code sample for reading in a file and displaying it.

#!/usr/bin/env python
 
forme = "f.txt";
 
# Read a file and print the contents to the terminal.
 
with open(forme) as f:
    content = f.read()
print content;
Admins-iMac-230:DBZ admin$ python read.py 
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1	localhost
255.255.255.255	broadcasthost
::1             localhost 
fe80::1%lo0	localhost

Here is what the output of this script looks like. I am printing the contents of a copy of the hosts file on an iMac.

You may also put this into a function; this allows you to call the code later.

#!/usr/bin/env python
 
forme = "f.txt";
 
def readfile():
	# Read a file and print the contents to the terminal.
 
	with open(forme) as f:
    		content = f.read()
	print content;
 
readfile()

As you can see, this is a very easy programming task.

Here is another way to achieve this.

#!/usr/bin/env python
 
import os
 
forme = "f.txt";
 
def readfile():
	response = os.system("cat " + forme)
 
readfile()

Using the cat command within python. Either way is good, but will not work on Windows.

No comments have been made. Use this form to start the conversation :)

Leave a Reply