Posted: . At: 10:36 AM. This was 10 years ago. Post ID: 7202
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


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


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.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.