Skip to content

January 27, 2013

Read From a File in Python

by noise

In the following example we read content of a file and print the result on the screen using a Python script.

Example 1

The file that will be read from is file.txt:

this is
just a
file.

The Python code for that is:

  #!/usr/local/bin/python
 
  import sys
 
  file = open('file.txt')
  buffer = file.readlines()
 
  for line in buffer:
      print line.rstrip()
 
  # EOF.

Note: we will use rstrip() to remove end of line character for every line we print.

Example 2

If we want to only display lines from our file.txt that contain a string, we will use the following code:

  #!/usr/local/bin/python
 
  import sys
 
  strToSearch = "just"
 
  file = open('file.txt')
  buffer = file.readlines()
 
  for line in buffer:
      if line.find(strToSearch) != -1:
          print line.rstrip()
 
# EOF.

Note: to search for a pattern on every line we will use find() function.

Read more from Python Noise

Leave a Reply

required
required

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments