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.
The file that will be read from is file.txt:
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.
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.