Read a file and print all the lines
#!/usr/bin/env python
import re
word=open("test.php", "r")
for i in word:
print i,
List all the lines starts with "Form:"
fhand = open('mbox-short.txt')
for line in fhand:
if line.startswith('From:') :
print line
Output:
From: stephen.marquard@uct.ac.za
From: louis@media.berkeley.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu
The output looks great since the only lines we are seeing are those which start with "From:", but why are we seeing the extra blank lines? This is due to that invisible newline character. Each of the lines ends with a newline, so the print statement prints the string in the variable line which includes a newline and then print adds another newline, resulting in the double spacing effect we see.
We could use line slicing to print all but the last character, but a simpler approach is to use the rstrip method which strips white-space from the right side of a string as follows:
List all the lines starts with "Form:" with no blank line:
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip() #removes the white-space from the right side of a string
if line.startswith('From:') :
print line
Output:
From: stephen.marquard@uct.ac.za
From: louis@media.berkeley.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu
From: cwen@iupui.edu
Before open the file check whether the file exist or not. Exception handling
filename=raw_input("Enter File Name : ")
try:
fob=open(filename)
except:
print 'File does not exist'
exit()
print 'FIle Exist'