>>> fhand = open('mbox.txt')
>>> print(fhand)
<_io.TextIOWrapper name = 'mbox.txt' mode='r' encoding='UTF-8'>
>>> stuff = 'Hello\nWorld'
>>> stuff
'Hello\nWorld'
>>> print(stuff)
Hello
World!
>>> stuff = 'X\nY'
>>> print(stuff)
X
Y
>>> len(stuff)
3
xfile = open('mbox.txt')
for cheese in xfile:
print(cheese)
fhand = open('mbox.txt')
count = 0
for line in fhand:
count = count + 1
print('Line Count:', count)
$ Python open.py
Line Count: 132045
We can read the while file (newlines and all) into a single string
>>> fhand = open('mbox-short.txt')
>>> inp = fhand.read()
>>> print(len(inp))
94626
>>> print(inpp[:20])
From stephen.marquar
We can put an if statement in our for loop to only print lines that meet some criteria
fhand = open('mbox-short.txt')
for line in fhand:
if line.startswitch('From:') :
print(line)
What are all these blank lines doing here?
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if line.startswitch('From:') :
print(line)
We can conveniently skip a line by using the continue statement
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not line.startswitch('From:') :
continue
print(line)
We can look for a string anywhere in a line as our selection criteria
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not '@uct.ac.za' in line :
continue
print(line)
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened: ', fname)
quit()
count = 0
for line in fhand:
if line.startswith('Subject:') :
count = count + 1
print('There were', count, 'subject lines in', fname)