















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Introduction to Python Programming
Typology: Lecture notes
1 / 23
This page cannot be seen from the preview
Don't miss anything!
















A text file can be thought of as a sequence of lines From [email protected] Sat Jan 5 09:14:16 2008 Return-Path: Date: Sat, 5 Jan 2008 09:12:18 - 0500 To: [email protected] From: [email protected] Subject: [sakai] svn commit: r39772 - content/branches/ Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=
A text file can be thought of as a sequence of lines From [email protected] Sat Jan 5 09:14:16 2008 Return-Path: Date: Sat, 5 Jan 2008 09:12:18 - 0500 To: [email protected] From: [email protected] Subject: [sakai] svn commit: r39772 - content/branches/ Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=
Reading Files in Python
We can read the whole file (newlines and all) into a single string
We can put an if statement in our for loop to only print lines that meet some criteria
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) From [email protected] Sat Jan 5 09:14:16 2008 X-Authentication-Warning: set sender to [email protected] using – f From: [email protected] Author: [email protected] From [email protected] Fri Jan 4 07:02:32 2008 X-Authentication-Warning: set sender to [email protected] using - f...
fname = input('Enter the file name: ') fhand = open(fname) count = 0 for line in fhand: if line.startswith('Subject:') : count = count + 1 print('There were', count, 'subject lines in', fname)