Skip to content

Posts from the ‘Python Noise’ Category

27
Jan

Read From a File in Python

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.

Read more »