Python - Files.

Slides:



Advertisements
Similar presentations
Python Basics: Statements Expressions Loops Strings Functions.
Advertisements

COMP234 Perl Printing Special Quotes File Handling.
Reading Files Chapter 7 Python for Informatics: Exploring Information
Files in Python Input techniques. Input from a file The type of data you will get from a file is always string or a list of strings. There are two ways.
Topics This week: File input and output Python Programming, 2/e 1.
TM 331: Computer Programming Introduction to Class, Introduction to Programming.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
Python for Informatics: Exploring Information
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Python Conditionals chapter 5
C Programming – Part 3 Arrays and Strings.  Collection of variables of the same type  Individual array elements are identified by an integer index 
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
Files Tutor: You will need ….
1 CSC 221: Introduction to Programming Fall 2011 Input & file processing  input vs. raw_input  files: input, output  opening & closing files  read(),
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
File input and output and conditionals Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas.
File I/O Ruth Anderson UW CSE 140 Winter File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
Python for Informatics: Exploring Information
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Python: File Directories What is a directory? A hierarchical file system that contains folders and files. Directory (root folder) Sub-directory (folder.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Loop Structures and Booleans Zelle - Chapter 8 Charles Severance - Textbook: Python Programming: An Introduction to Computer Science,
Chapter 4 Computing With Strings Charles Severance Textbook: Python Programming: An Introduction to Computer Science, John Zelle.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
Reading Files Chapter 7 Python for Everybody
Topic: File Input/Output (I/O)
Strings CSCI 112: Programming in C.
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
Python - Lists.
Regular Expressions Chapter 11 Python for Everybody
Python Lists Chapter 8 Python for Everybody
Chapter 4 Computing With Strings
IST256 : Applications Programming for Information Systems
Strings Part 1 Taken from notes by Dr. Neil Moore
Python for Informatics: Exploring Information
Exceptions and files Taken from notes by Dr. Neil Moore
And now for something completely different . . .
Structured Programming (Top Down Step Refinement)
Python - Conditional Execution
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
File Handling Programming Guides.
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
File IO and Strings CIS 40 – Introduction to Programming in Python
Loop Structures and Booleans Zelle - Chapter 8
Exceptions and files Taken from notes by Dr. Neil Moore
Python - Strings.
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
Introduction to Python: Day Three
Using Text Files in Python
Input from the Console This video shows how to do CONSOLE input.
CMSC201 Computer Science I for Majors Lecture 13 – File I/O
Topics Introduction to File Input and Output
Introduction to Computer Science
Reading Data From and Writing Data To Text Files
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
“Everything Else”.
Decision Structures Zelle - Chapter 7
CSE 231 Lab 5.
Topics Introduction to File Input and Output
Files A common programming task is to read or write information from/to a file.
Lecture 31 – Practice Exercises 7
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Introduction to Computer Science
Presentation transcript:

Python - Files

File Processing -- A text file can be thought of as a sequence of lines From jeromitc@umail.iu.edu Wed Jun 10 09:14:16 2015 Return-Path: <postmaster@umail.iu.edu> Date: Wed Jun 10 09:14:16 2015 To: jasmith@gmail.com From: jeromitc@umail.iu.edu Subject: Hello! Details: How are you?

Opening a File -- Before reading the contents of a file, Python needs to know the file and the operation on that file -- This is done with the open() function -- open() returns a “file handle” - a variable used to perform operations on the file -- Kind of like “File -> Open” in a Word Processor

Using open() handle = open(filename, mode) fhand = open('mbox.txt', 'r') -- returns a handle use to manipulate the file -- filename is a string -- mode is optional and should be 'r' if reading from the file and 'w' if writing to the file. http://docs.python.org/lib/built-in-funcs.html

What is a Handle? >>> fhand = open('mbox.txt') >>> print fhand <open file 'mbox.txt', mode 'r' at 0x1005088b0>

When Files are Missing >>> fhand = open('stuff.txt') Traceback (most recent call last): File "<stdin>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'stuff.txt'

The newline Character >>> stuff = 'Hello\nWorld!’ >>> print stuff Hello World! >>> stuff = 'X\nY’ >>> print stuff X Y >>> len(stuff) 3 -- Use the "newline" character to indicate when a line ends -- It is represented as a \n in strings -- Newline is still one character not two

File Processing -- A text file can be thought of as a sequence of lines From jeromitc@umail.iu.edu Wed Jun 10 09:14:16 2015 Return-Path: <postmaster@umail.iu.edu> Date: Wed Jun 10 09:14:16 2015 To: jasmith@gmail.com From: jeromitc@umail.iu.edu Subject: Hello! Details: How are you?

File Processing -- A text file has newlines at the end of each line From jeromitc@gmail.com Sat Jan 5 9:14:16 2015\n Return-Path: <postmaster@collab.githubproject.org>\n Date: Sat, 5 Jan 2008 09:12:18 -0500\nTo: source@collab.githubproject.org\nFrom: jeromitc@gmail.com\nSubject: [github] svn commit: r39772 - content/branches/\nDetails: http://source.githubproject.org/viewsvn/?view=rev&rev=39772\n

File Handle as a Sequence -- A file handle open for read can be treated as a sequence of strings where each line in the file is a string in the sequence -- Use the for statement to iterate through a sequence -- Remember - a sequence is an ordered set xfile = open('mbox.txt') for cheese in xfile: print cheese

Counting Lines in a File fhand = open('mbox.txt') count = 0 for line in fhand: count = count + 1 print 'Line Count:', count $ python open.py Line Count: 132045 -- Open a file read-only -- Use a for loop to read each line -- Count the lines and print out the number of lines

Searching Through a File fhand = open('mbox-short.txt') for line in fhand: if line.startswith('From:') : print line -- An if statement can be used in the for loop to only print lines that meet some criteria

OOPS! What are all these blank lines doing here? From: micheal.jefferson@ecsu.edu From: louis@berkeley.edu From: zqian@standford.edu From: rjlowe@iupui.edu ...

OOPS! What are all these blank lines doing here? Each line from the file has a newline at the end. The print statement adds a newline to each line. From: micheal.jefferson@ecsu.edu\n \n From: louis@berkeley.edu\n From: zqian@standford.edu\n From: rjlowe@iupui.edu\n ...

Searching Through a File (fixed) fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if line.startswith('From:') : print line From: micheal.jefferson@ecsu.edu From: louis@berkeley.edu From: zqian@standford.edu From: rjlowe@iupui.edu .... -- We can strip the whitespace from the right hand side of the string using rstrip() from the string library -- The newline is considered "white space" and is stripped

Skipping with continue fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if not line.startswith('From:') : continue print line …Convienently skip a line by using the continue statement

Using in to select lines fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if not '@gmail.com' in line : continue print line -- We can look for a string anywhere in a line as our selection criteria From jeromitc@gmail.com Sat Jan 5 09:14:16 2008 X-Authentication-Warning: set sender to jeromitc@gmail.com using –f From: jeromitc@gmail.comAuthor: jeromitc@gmail.com From jane.doe@gmail.com Fri Jan 4 07:02:32 2008 X-Authentication-Warning: set sender to jane.doe@gmail.com using -f...

fname = raw_input('Enter the file name: ') Prompt for 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 Enter the file name: mbox.txt There were 1697 subject lines in mbox.txt Enter the file name: mbox-short.txt There were 17 subject lines in mbox-short.txt

fname = raw_input('Enter the file name: ') try: fhand = open(fname) except: print 'File cannot be opened:', fname exit() count = 0 for line in fhand: if line.startswith('Subject:') : count = count + 1 print 'There were', count, 'subject lines in', fname Bad File Names Enter the file name: mbox.txt There were 1697 subject lines in mbox.txt Enter the file name: na na boo boo File cannot be opened: na na boo boo