Lecture 17: Files. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/17. Department of Computer Science University College Cork

Size: px
Start display at page:

Download "Lecture 17: Files. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/17. Department of Computer Science University College Cork"

Transcription

1 Lecture 17: Files CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/17 Department of Computer Science University College Cork

2 Summary Python s sequential file-processing capabilities: Sequential text files. Read, write and append mode. with statement. Binary files. 1

3 Files in Python

4 Files Computer systems use files to store all sorts of stuff: documents, programs (source and executables), images, webpages, lecture slides, etc. Files are persistent: data preserved between executions of program, unlike ephemeral prog. data. 2

5 File types In the Python world files fall into two broad categories: Text files Comprise printable text characters only Convenient and widely used for: programs (source), webpages, Can be read/modified by simple text-editor tools Not system- or application-dependent Binary files e.g. jpg images,.doc files, Typically not human readable (without specific software) Typically system or application dependent 3

6 Sequential Text Files

7 Python s text-file model Python text files contains a linear sequence of characters encoded in ASCII or Unicode separated into lines Sequential file processing: File processed in read-only or write-only mode Progress through a file from beginning to end without backing up (More efficient than hopping around) 4

8 Text files: Unix vs Windows Windows and Unix systems use diff. conventions for marking line breaks: Sym. Char. ASCII (hex) Unix LF \n 0A Windows CR LF \r\n 0A 0D Unix dos2unix and unix2dos useful for conversions 5

9 Python s text-file model Python used open-read-close idiom for seq. file procesing Typical code skeleton: file name = whatever.txt textfile = open(file name, r ) # (1) Must open before use # (2) Read through the file from begining to end textfile. close () # (3) close when done Specify file mode when opening ( r means read only) variable textfile points to file object bundle of housekeeping info relating to file 6

10 Python s file-reading operations Old-fashioned way f.readline() f.read() f.readlines() Better way (usually) Use file iterator (later) readline reads a single line (as a string, including newline); empty string signifies end of file read devours entire file and returns contents as single string readlines devours entire file and returns contents as list of lines (strings) 7

11 Reading file one line at a time readline Code snippet to count the lines in a file; open and close omitted here to declutter num lines = 0 line = textfile. readline () while len( line ) > 0: num lines += 1 line = textfile. readline () print (...) 8

12 Reading file in one go read and readlines The same thing using read and readlines text = textfile.read() num lines = text.count( \n ) Quibble: Assumes last line of file contains a newline. print (...) text = textfile. readlines () num lines = len(text) readlines devours entire file and returns contents as list of lines (strings) print (...) 9

13 File iterators Can use for loop to step through file line by line... for line in textfile : # do stuff... For each iteration line takes on value of a line from file and teh loop body executed 10

14 File iterators cont d The line-counting application again: name = debanks.txt textfile = open(name, r ) num lines = 0 for line in textfile : num lines += 1 print( File '%s' contains %i lines % (name, num lines)) textfile. close () 11

15 File iterators and with statement A slightly neater version line-counting application again: name = debanks.txt with open(name, r ) as textfile : num lines = 0 for line in textfile : num lines += 1 print( File '%s' contains %i lines % (name, num lines)) with statement provides envelope wrapped around file code embodies both open statement and close statement (invisable) 12

16 Critique of solution name = debanks.txt with open(name, r ) as textfile : num lines = 0 for line in textfile : num lines += 1 print( File '%s' contains %i lines % (name, num lines)) Problems can occur if file can t be found file can t be opened (corrupted?) file can t be read (not text?) among others Our code will crash in such situations More robust approach to catch these; need exception handling later 13

17 File Writing

18 Python s other file modes r w a b read only write only append at end of file binary (for non-text files) 14

19 Writing to files Use file mode w when opening to write to a file Previous contents of file are erased Use write function to write strings to file file. write( Hello, World! ) Each write adds to the file after previously written stuff 15

20 Writing to files Application to generate file containing powers of natural numbers file = open( table of powers.txt, w ) LIMIT = 10 header = Table of Powers from 1 to %d\n % LIMIT bar = = len(header) + \n\n file. write(header) file. write(bar) for n in range(1, LIMIT + 1): file. write( %3d %5d %5d\n % (n, n 2, n 3)) 16

21 Writing to files cont d Final contents of table-of-powers.txt: Table of Powers from 1 to 10 =============================

22 Appending to a file Use file mode a to append to file def log(msg): # Append message 'msg' to the log file file = open( logfile. txt, a ) file. write(msg+ \n ) file. close () message = input( Enter message to be added to log: ) log(message) Each write adds an fresh line tacked on to the end of the existing file contents (i.e. does not erase old file contents) 18

23 File Demos

24 Simple file demos Application to print copy of a text file with line numbers prepended. file name = input( Please enter a file name: ) file = open(file name, r ) line num = 0 for line in file : line num = line num + 1 print( %3d %2d %s % (line num, len(line), line), end = ) 19

25 Illustration Text file debanks.txt contains: ===================================== The Banks of My Own Lovely Lee ===================================== How oft do my thoughts in their fancy take flight To the home of my childhood away, To the days when each patriot s vision seem d bright Ere I dreamed that those joys should decay. When my heart was as light as the wild winds that blow Down the Mardyke through each elm tree, Where I sported and play d neath each green leafy shade On the banks of my own lovely Lee. Program generates the following output: ===================================== The Banks of My Own Lovely Lee ===================================== How oft do my thoughts in their fancy take flight To the home of my childhood away, To the days when each patriot s vision seem d bright Ere I dreamed that those joys should decay When my heart was as light as the wild winds that blow Down the Mardyke through each elm tree, Where I sported and play d neath each green leafy shade 20

26 Simple pattern finding tool Develop a tool that hunts through a text file printing only those lines on which a particular pattern occurs. Idea (suppose pattern is P): Open file and read through it line by line For each line check if P occurs and if so print the line 21

27 Illustration Executing grep("debanks.txt", "the") produces: [l4, c26]: How oft do my thoughts in their fancy take flight [l5, c3 ]: To the home of my childhood away, [l6, c3 ]: To the days when each patriot s vision seem d brigh [l8, c30]: When my heart was as light as the wild winds that b [l9, c5 ]: Down the Mardyke through each elm tree, [l11, c3 ]: On the banks of my own lovely Lee. Have included line and column numbers for clarity. 22

28 Code def grep( filename, pattern ): file = open(filename, r ) line num = 0 for line in file : if line. find (pattern)!= 1: col num = line. index(pattern) print( [ l% 3d, c% 2d]: %s % (line num, col num, line[: line num = line num

29 Simple text analysis II

30 Text analysis revisited Write a Python program to read the contents of a text file and to output the number of lines, words and letters found therein. 24

31 Illustration ===================================== The Banks of My Own Lovely Lee ===================================== How oft do my thoughts in their fancy take flight To the home of my childhood away, To the days when each patriot s vision seem d bright Ere I dreamed that those joys should decay. When my heart was as light as the wild winds that blow Down the Mardyke through each elm tree, Where I sported and play d neath each green leafy shade On the banks of my own lovely Lee. Result: Number of lines, words, chars = 12, 80,

32 Text analysis revisited Use following string-manipulating helper functions purge to remove punctuation stats to analyze contents of a string Integrate with file-reading aparatus: Read through file line by line Use stats to calculated number of words and chars on line (Sum these as we go) 26

33 Text analysis revisited def depunctuated(text): # Return filtered version of ' text ' with all punctuation # marks removed.... def stats (text ): # Return the number of letters and words in string parameter # 'text '. Assume no words split across lines.... def word count(filename ): # Return the number of lines, words and letters in # the file named 'filename'... 27

34 Stripping out punctuation def depunctuated(text): # Return filtered version of ' text ' with all punctuation # marks removed. MARKS =.,;:?!\ '() dep = for c in text : if c not in MARKS: dep = dep + c return dep 28

35 Counting letters and words def stats (text ): # Return the number of letters and words in string parameter # 'text '. Assume no words split across lines. 29

36 Counting letters and words def stats (text ): # Return the number of letters and words in string parameter # 'text '. Assume no words split across lines. unpunctuated = depunctuated(text) letters = [x for x in unpunctuated if x. isalpha ()] num letters = len( letters ) 29

37 Counting letters and words def stats (text ): # Return the number of letters and words in string parameter # 'text '. Assume no words split across lines. unpunctuated = depunctuated(text) letters = [x for x in unpunctuated if x. isalpha ()] num letters = len( letters ) words = unpunctuated.split () num words = len(words) return ( num letters, num words) 29

38 Function wordcount def word count(filename ): # Return the number of lines, words and letters in # the file named 'filename' f = open(filename, r ) line count, word count, char count = 0, 0, 0 for line in f : c, w = stats( line ) line count = line count + 1 char count = char count + c word count = word count + w f. close () return line count, word count, char count 30

39 The main program num lines, num words, num chars = word count( debanks.txt ) print( Number of lines, words, chars = %d, %d, %d \ % (num lines, num words, num chars)) 31

40 Text censoring application

41 Censoring text Develop a function that takes the name of a text file and the produces a censored copy in which all the rude words have been bleeped out (with asterisks). 32

42 Illustration curses.txt Damn, blast and double damn! Fiddlesticks! FIDDLESTICKS!!! Fiddle-damn-sticks! Blasted, damned fiddlesticks. clean curses.txt ****, ***** and double ****! ************! ************!!! Fiddle-damn-sticks! Blasted, damned ************. 33

43 Outline def bleeped(word): # Return a bowlderized version of parameter 'word' with # any black listed word replaced by asterisks. Ignore any # non letters at the beginning or end of ' word'.... def censor line ( line ): # Return censored version of the text in string parameter # ' line ' while preserving word breaks and punctuation.... def censor file ( filename ): # Generate a modified copy of the named text file containing # a censored version of the text

44 def censor file ( filename ): # Generate a modified copy of the named text file containing # a censored version of the text. infile = open(filename, r ) outfile = open( clean +filename, w ) for line in infile : clean line = censor line ( line ) outfile. write( clean line ) 35

45 def censor line ( line ): # Return censored version of the text in string parameter # ' line ' while preserving word breaks and punctuation. words = line. split () for i in range(len(words)): words[ i ] = bleeped(words[i ]) return. join (words) + \n 36

46 def bleeped(word): # Return a bowlderized version of parameter 'word' with # any black listed word replaced by asterisks. Ignore any # non letters at the beginning or end of 'word'. # Set ' first ' and ' last ' to indices of leftmost and rightmost letter first = 0 while first < len(word) and not word[ first ]. isalpha (): first = first + 1 last = len(word) 1 while last > first and not word[ last ]. isalpha (): last = last 1 stem = word[ first : last + 1] prestem = word[: first ] poststem = word[last + 1:] if stem.lower() in BLACK LIST: stem = MASK len(stem) return prestem+stem+poststem 37

47 Binary Files

48 Binary files Binary files used for: images, audio, executable,... Python treats binary files as linear sequence of bytes Use same open-(read/write)-close idiom as text files Use f.read(n) for reading (n bytes) f.write(x) for writing (but x must contain byte values) 38

49 Simple GIF Checker Application to check if a file is a GIF. Note: GIF s have a distinctive header in their first four bytes. def is gif (fname): f = open(fname, br ) first4 = tuple(f.read(4)) gif header = (0x47, 0x49, 0x46, 0x38) return ( first4 == gif header) 39

50 Simple file comparer Write application to compare two file to seeof they are identical (byte for byte) Idea: read through files chunk by chunk, checking that the two chunks at each step match (byte for byte); any mismatch signifies that]files are not identical 40

51 Simple file comparer cont d def are equal (fname1, fname2): CHUNKSIZE = 1000 try: f1 = open(fname1, br ) f2 = open(fname2, br ) except IOError: print( Problems opening files '%s' or '%s'. % (fname1, fnam exit () # Read through f1, f2 chunk by chunk, checking that the chunks # match (byte for byte ); set Boolean 'mismatch' is if discrepency f1. close () f1. close () 41

52 Simple file comparer cont d bytes1 = f1.read(chunksize) bytes2 = f2.read(chunksize) mismatch = bytes1!= bytes2 while not mismatch and len(bytes1)!= 0 and len(bytes2)!= 0: bytes1 = f1.read(chunksize) bytes2 = f2.read(chunksize) mismatch = bytes1!= bytes2 42

53 Pickling

54 Pickling Pickling allows contents stored in a Python structure (list, distionary etc) to be stored in a file and to be restored/reconstitued later Useful to preverve data across sucessive prohgrame executions 43

55 Pickling demo To store prog. x, y, z: import pickle data in vars. To re-store prog. data back into vars. x, y, z: import pickle f = open( progstate, w ) pickle. dump(x,f) pickle. dump(y,f) pickle. dump(z,f) f. close () f = open( progstate, r ) x = pickle.load(f) y = pickle.load(f) z = pickle.load(f) f. close () 44

56 Back Material

57 Notes and Acknowledgements Reading Code Acknowledgements 45

Lecture 4: Simple Input-Calculate-Output Programs

Lecture 4: Simple Input-Calculate-Output Programs Lecture 4: Simple Input-Calculate-Output Programs CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2017/18 Department of Computer Science University College Cork input Statement Python s

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 5 Part 3 & Review The Department of Computer Science Multi-Line Strings Files: Multi-line Strings A file is a sequence of

More information

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming File Operations Files are persistent data storage titanicdata.txt in PS07 Persistent vs. volatile memory. The bit as the unit of information. Persistent = data that is not dependent on a running program

More information

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley Lecture 11: while loops CS1068+ Introductory Programming in Python Dr Kieran T. Herley Python s while loop. Summary Department of Computer Science University College Cork 2017-2018 KH (24/10/17) Lecture

More information

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming File Operations Files are persistent data storage titanicdata.txt in PS06 Persistent vs. volatile memory. The bit as the unit of information. Persistent = data that is not dependent on a program (exists

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 5 Part 3 & Review The Department of Computer Science Multi-Line Strings -2-1 Files: Multi-line Strings A file is a sequence

More information

Chapter 6: Files and Exceptions. COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016

Chapter 6: Files and Exceptions. COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016 Chapter 6: Files and Exceptions COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016 Introduction to File Input and Output Concept: When a program needs to save data for later use, it writes the data in a

More information

Files on disk are organized hierarchically in directories (folders). We will first review some basics about working with them.

Files on disk are organized hierarchically in directories (folders). We will first review some basics about working with them. 1 z 9 Files Petr Pošík Department of Cybernetics, FEE CTU in Prague EECS, BE5B33PRG: Programming Essentials, 2015 Requirements: Loops Intro Information on a computer is stored in named chunks of data called

More information

Digital Systems COE 202. Digital Logic Design. Dr. Muhamed Mudawar King Fahd University of Petroleum and Minerals

Digital Systems COE 202. Digital Logic Design. Dr. Muhamed Mudawar King Fahd University of Petroleum and Minerals Digital Systems COE 202 Digital Logic Design Dr. Muhamed Mudawar King Fahd University of Petroleum and Minerals Welcome to COE 202 Course Webpage: http://faculty.kfupm.edu.sa/coe/mudawar/coe202/ Lecture

More information

Lecture 15: Dictionaries

Lecture 15: Dictionaries Lecture 15: Dictionaries CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/19 Department of Computer Science University College Cork Summary Python s dictionary concept. 1 Dictionaries

More information

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17 CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 1 Discussion Sections 02-08, 16, 17 Adapted from slides by Sue Evans et al. 2 Learning Outcomes Become familiar with input and output (I/O) from

More information

Textbook. Topic 8: Files and Exceptions. Files. Types of Files

Textbook. Topic 8: Files and Exceptions. Files. Types of Files Textbook Topic 8: Files and A common mistake that people make when trying to design something completely foolproof is to underestimate the ingenuity of complete fools. -Douglas Adams 1 Strongly Recommended

More information

Lecture 2: Writing Your Own Class Definition

Lecture 2: Writing Your Own Class Definition Lecture 2: Writing Your Own Class Definition CS6507 Python Programming and Data Science Applications Dr Kieran T. Herley 2017-2018 Department of Computer Science University College Cork Summary Writing

More information

File Processing. CS 112: Introduction to Programming: File Processing Sequence. File Processing. File IO

File Processing. CS 112: Introduction to Programming: File Processing Sequence. File Processing. File IO File Processing CS 112: Introduction to Programming: File IO Coming up: File Processing 1 File Processing Sequence 1. Open the file 2. Read from the file 3. Close the file In some cases, not properly closing

More information

Lecture 10: Strings. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lecture 10: Strings. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork Lecture 10: Strings CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/19 Department of Computer Science University College Cork Summary 1 Python text: data type str String sequences of

More information

Command Interpreters. command-line (e.g. Unix shell) On Unix/Linux, bash has become defacto standard shell.

Command Interpreters. command-line (e.g. Unix shell) On Unix/Linux, bash has become defacto standard shell. Command Interpreters A command interpreter is a program that executes other programs. Aim: allow users to execute the commands provided on a computer system. Command interpreters come in two flavours:

More information

#11: File manipulation Reading: Chapter 7

#11: File manipulation Reading: Chapter 7 CS 130R: Programming in Python #11: File manipulation Reading: Chapter 7 Contents File manipulation Text ASCII files Binary files - pickle Exceptions File manipulation Electronic files Files store useful

More information

File I/O in Python Formats for Outputs CS 8: Introduction to Computer Science, Winter 2018 Lecture #12

File I/O in Python Formats for Outputs CS 8: Introduction to Computer Science, Winter 2018 Lecture #12 File I/O in Python Formats for Outputs CS 8: Introduction to Computer Science, Winter 2018 Lecture #12 Ziad Matni Dept. of Computer Science, UCSB Administrative Homework #7 is DUE on MONDAY (3/12) Lab

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 4 (End of Chapter) File IO Coming up: File Processing 1 File Processing! The process of opening a file involves associating a file on disk

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017 Chapter 6: Files and Exceptions COSC 1436, Spring 2017 Hong Sun 3/6/2017 Function Review: A major purpose of functions is to group code that gets executed multiple times. Without a function defined, you

More information

Files. Reading from a file

Files. Reading from a file Files We often need to read data from files and write data to files within a Python program. The most common type of files you'll encounter in computational biology, are text files. Text files contain

More information

Loop structures and booleans

Loop structures and booleans Loop structures and booleans Michael Mandel Lecture 7 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture07final.ipynb

More information

Sequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word?

Sequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word? Motivation: How to count the number of vowels in a word? Sequences and Loops o You re given words like 'boston', 'wellesley', 'needham', 'lynn', etc. o Tasks: o count the number of vowels in a word. o

More information

PROGRAM COMPILATION MAKEFILES. Problem Solving with Computers-I

PROGRAM COMPILATION MAKEFILES. Problem Solving with Computers-I PROGRAM COMPILATION MAKEFILES Problem Solving with Computers-I The compilation process Source code Source code: Text file stored on computers hard disk or some secondary storage Compiler Executable hello.cpp

More information

Lecture 18: Lists II. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lecture 18: Lists II. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork Lecture 18: Lists II CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/19 Department of Computer Science University College Cork Summary More on Python s lists. Sorting and reversing.

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Objectives æ To understand the programming pattern simple decision and its implementation

More information

Data Representation COE 301. Computer Organization Prof. Muhamed Mudawar

Data Representation COE 301. Computer Organization Prof. Muhamed Mudawar Data Representation COE 30 Computer Organization Prof. Muhamed Mudawar College of Computer Sciences and Engineering King Fahd University of Petroleum and Minerals Presentation Outline Positional Number

More information

Lecture 2: SQL Basics CS1106/CS5021/CS6503 Introduction to Relational Databases. Brief Note on Naming Conventions. Our Running Example.

Lecture 2: SQL Basics CS1106/CS5021/CS6503 Introduction to Relational Databases. Brief Note on Naming Conventions. Our Running Example. Lecture 2: SQL Basics CS1106/CS5021/CS6503 Introduction to Relational Databases Dr Kieran T. Herley Summary Review of relation model. Simple SELECT-FROM and SIMPLE-FROM-WHERE queries. SQL s operators.

More information

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

CS107, Lecture 3 Bits and Bytes; Bitwise Operators CS107, Lecture 3 Bits and Bytes; Bitwise Operators reading: Bryant & O Hallaron, Ch. 2.1 This document is copyright (C) Stanford Computer Science and Nick Troccoli, licensed under Creative Commons Attribution

More information

Python Tutorial. Day 2

Python Tutorial. Day 2 Python Tutorial Day 2 1 Control: Whitespace in perl and C, blocking is controlled by curly-braces in shell, by matching block delimiters, if...then...fi in Python, blocking is controlled by indentation

More information

Lecture 2: SQL Basics

Lecture 2: SQL Basics Lecture 2: SQL Basics CS1106/CS5021/CS6503 Introduction to Relational Databases Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (19/09/17) Lecture 2: SQL Basics

More information

Fundamentals of Programming (Python) File Processing. Ali Taheri Sharif University of Technology Spring 2018

Fundamentals of Programming (Python) File Processing. Ali Taheri Sharif University of Technology Spring 2018 Fundamentals of Programming (Python) File Processing Ali Taheri Sharif University of Technology Outline 1. Sources of Input 2. Files 3. Opening a File 4. Opening Modes 5. Closing a File 6. Writing to a

More information

Sequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word?

Sequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word? Motivation: How to count the number of vowels in a word? Sequences and Loops o You re given words like 'Boston', 'Wellesley', 'abracadabra', 'bureaucracies', etc. o Tasks: o count the number of vowels

More information

Simple Lexical Analyzer

Simple Lexical Analyzer Lecture 7: Simple Lexical Analyzer Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (03/10/17) Lecture 7: Simple Lexical Analyzer 2017-2018 1 / 1 Summary Use of jflex

More information

Fundamentals of Python: First Programs. Chapter 4: Strings and Text Files

Fundamentals of Python: First Programs. Chapter 4: Strings and Text Files Fundamentals of Python: First Programs Chapter 4: Strings and Text Files Objectives After completing this chapter, you will be able to Access individual characters in a string Retrieve a substring from

More information

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python Outline Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer Universität des Saarlandes October 6th, 2009 Outline Outline Today s Topics: 1 More Examples 2 Cool Stuff 3 Text Processing

More information

CS 112: Intro to Comp Prog

CS 112: Intro to Comp Prog CS 112: Intro to Comp Prog Importing modules Branching Loops Program Planning Arithmetic Program Lab Assignment #2 Upcoming Assignment #1 Solution CODE: # lab1.py # Student Name: John Noname # Assignment:

More information

File processing and decision structures

File processing and decision structures File processing and decision structures Michael Mandel Lecture 4 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture04final.ipynb

More information

Lecture 7: Functions. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lecture 7: Functions. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork Lecture 7: Functions CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/19 Department of Computer Science University College Cork Summary Functions in Python. Terminology and execution.

More information

Reading and manipulating files

Reading and manipulating files Reading and manipulating files Goals By the end of this lesson you will be able to Read files without using text editors Access specific parts of files Count the number of words and lines in a file Sort

More information

CPSC 301: Computing in the Life Sciences Lecture Notes 16: Data Representation

CPSC 301: Computing in the Life Sciences Lecture Notes 16: Data Representation CPSC 301: Computing in the Life Sciences Lecture Notes 16: Data Representation George Tsiknis University of British Columbia Department of Computer Science Winter Term 2, 2015-2016 Last updated: 04/04/2016

More information

CS 11 python track: lecture 3. n Today: Useful coding idioms

CS 11 python track: lecture 3. n Today: Useful coding idioms CS 11 python track: lecture 3 Today: Useful coding idioms Useful coding idioms "Idiom" Standard ways of accomplishing a common task Using standard idioms won't make your code more correct, but more concise

More information

1 Modules 2 IO. 3 Lambda Functions. 4 Some tips and tricks. 5 Regex. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 30, / 22

1 Modules 2 IO. 3 Lambda Functions. 4 Some tips and tricks. 5 Regex. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 30, / 22 1 Modules 2 IO 3 Lambda Functions 4 Some tips and tricks 5 Regex Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 30, 2009 1 / 22 What are they? Modules are collections of classes or functions

More information

CSC102 INTRO TO PROGRAMMING WITH PYTHON LECTURE 12 LISTING TO ONE SIDE MICHAEL GROSSBERG

CSC102 INTRO TO PROGRAMMING WITH PYTHON LECTURE 12 LISTING TO ONE SIDE MICHAEL GROSSBERG CSC102 INTRO TO PROGRAMMING WITH PYTHON LECTURE 12 LISTING TO ONE SIDE MICHAEL GROSSBERG LISTS AGAIN IS IT ON THE MIDTERM YES! NO! WE LEARNED THIS STUFF (LISTS) ALREADY WE ARE GOING INTO MORE DEPTH IF

More information

CS112 Lecture: Primitive Types, Operators, Strings

CS112 Lecture: Primitive Types, Operators, Strings CS112 Lecture: Primitive Types, Operators, Strings Last revised 1/24/06 Objectives: 1. To explain the fundamental distinction between primitive types and reference types, and to introduce the Java primitive

More information

System Programming. Unix Shells

System Programming. Unix Shells Content : Unix shells by Dr. A. Habed School of Computer Science University of Windsor adlane@cs.uwindsor.ca http://cs.uwindsor.ca/ adlane/60-256 Content Content 1 Introduction 2 Interactive and non-interactive

More information

Administrivia. CMSC 216 Introduction to Computer Systems Lecture 24 Data Representation and Libraries. Representing characters DATA REPRESENTATION

Administrivia. CMSC 216 Introduction to Computer Systems Lecture 24 Data Representation and Libraries. Representing characters DATA REPRESENTATION Administrivia CMSC 216 Introduction to Computer Systems Lecture 24 Data Representation and Libraries Jan Plane & Alan Sussman {jplane, als}@cs.umd.edu Project 6 due next Friday, 12/10 public tests posted

More information

- c list The list specifies character positions.

- c list The list specifies character positions. CUT(1) BSD General Commands Manual CUT(1)... 1 PASTE(1) BSD General Commands Manual PASTE(1)... 3 UNIQ(1) BSD General Commands Manual UNIQ(1)... 5 HEAD(1) BSD General Commands Manual HEAD(1)... 7 TAIL(1)

More information

2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1

2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1 2.1 Indefinite Loops The final kind of control flow is Python s indefinite loop, the while loop. It functions much like the for loop in that it repeatedly executes some body of statements. The difference

More information

Chapter 14: Files and Streams

Chapter 14: Files and Streams Chapter 14: Files and Streams Files and the File and Directory Temporary storage Classes Usually called computer memory or random access memory (RAM) Variables use temporary storage Volatile Permanent

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Objectives. Connecting with Computer Science 2

Objectives. Connecting with Computer Science 2 Objectives Learn why numbering systems are important to understand Refresh your knowledge of powers of numbers Learn how numbering systems are used to count Understand the significance of positional value

More information

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

Goals of C  The Goals of C (cont.)  Goals of this Lecture The Design of C: A Rational Reconstruction Goals of this Lecture The Design of C: A Rational Reconstruction Help you learn about: The decisions that were available to the designers of C The decisions that were made by the designers of C Why? Learning

More information

File Input/Output in Python. October 9, 2017

File Input/Output in Python. October 9, 2017 File Input/Output in Python October 9, 2017 Moving beyond simple analysis Use real data Most of you will have datasets that you want to do some analysis with (from simple statistics on few hundred sample

More information

Scheme: Strings Scheme: I/O

Scheme: Strings Scheme: I/O Scheme: Strings Scheme: I/O CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Wednesday, April 5, 2017 Glenn G. Chappell Department of Computer Science University of

More information

DATA STRUCTURE AND ALGORITHM USING PYTHON

DATA STRUCTURE AND ALGORITHM USING PYTHON DATA STRUCTURE AND ALGORITHM USING PYTHON Advanced Data Structure and File Manipulation Peter Lo Linear Structure Queue, Stack, Linked List and Tree 2 Queue A queue is a line of people or things waiting

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

The Big Python Guide

The Big Python Guide The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26, Part IV More on Python Compact Course @ Max-Planck, February 16-26, 2015 36 More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith ("

More information

Announcements COMP 141. Writing to a File. Reading From a File 10/18/2017. Reading/Writing from/to Files

Announcements COMP 141. Writing to a File. Reading From a File 10/18/2017. Reading/Writing from/to Files Announcements COMP 141 Reading/Writing from/to Files Reminders Program 5 due Thurs., October 19 th by 11:55pm Solutions to selected problems from Friday s lab are in my Box.com directory (LoopLab.py) Programming

More information

CS Programming Languages: Python

CS Programming Languages: Python CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer

More information

Introduction to programming Lecture 4: processing les and counting words

Introduction to programming Lecture 4: processing les and counting words Introduction to programming Lecture 4: processing les and counting words UNIVERSITY OF Richard Johansson September 22, 2015 overview of today's lecture le processing splitting into sentences and words

More information

Advanced training. Linux components Command shell. LiLux a.s.b.l.

Advanced training. Linux components Command shell. LiLux a.s.b.l. Advanced training Linux components Command shell LiLux a.s.b.l. alexw@linux.lu Kernel Interface between devices and hardware Monolithic kernel Micro kernel Supports dynamics loading of modules Support

More information

CS116 - Module 10 - File Input/Output

CS116 - Module 10 - File Input/Output CS116 - Module 10 - File Input/Output Cameron Morland Winter 2018 Reminder: if you have not already, ensure you: Read Think Python, chapters 8, 12, 14. 1 Cameron Morland CS116 - Module 10 - File Input/Output

More information

Reminders. Lecture Outline. Lecture Agenda. Namespaces II. Namespaces I. COMP10001 Foundations of Computing PEP8, Modules and Files

Reminders. Lecture Outline. Lecture Agenda. Namespaces II. Namespaces I. COMP10001 Foundations of Computing PEP8, Modules and Files COMP10001 Foundations of Computing PEP8, Modules and Files Reminders Semester 1, 2017 Tim Baldwin & Egemen Tanin Grok Worksheets 8 11 due at the end of this week Have a go at the early-release tutesheet

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 15 File I/O All materials copyright UMBC unless otherwise noted Last Class We Covered Python s tuple data structure Tuples in functions (and as return values)

More information

COMS 6100 Class Notes 3

COMS 6100 Class Notes 3 COMS 6100 Class Notes 3 Daniel Solus September 1, 2016 1 General Remarks The class was split into two main sections. We finished our introduction to Linux commands by reviewing Linux commands I and II

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

File I/O, Benford s Law, and sets

File I/O, Benford s Law, and sets File I/O, Benford s Law, and sets Matt Valeriote 11 February 2019 Benford s law Benford s law describes the (surprising) distribution of first digits of many different sets of numbers. Read it about it

More information

1 Strings (Review) CS151: Problem Solving and Programming

1 Strings (Review) CS151: Problem Solving and Programming 1 Strings (Review) Strings are a collection of characters. quotes. this is a string "this is also a string" In python, strings can be delineated by either single or double If you use one type of quote

More information

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used)

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used) The design recipe Readings: HtDP, sections 1-5 (ordering of topics is different in lectures, different examples will be used) Survival and Style Guides CS 135 Winter 2018 02: The design recipe 1 Programs

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

Final Labs and Tutors

Final Labs and Tutors ICT106 Fundamentals of Computer Systems - Topic 2 REPRESENTATION AND STORAGE OF INFORMATION Reading: Linux Assembly Programming Language, Ch 2.4-2.9 and 3.6-3.8 Final Labs and Tutors Venue and time South

More information

The Design of C: A Rational Reconstruction (cont.)

The Design of C: A Rational Reconstruction (cont.) The Design of C: A Rational Reconstruction (cont.) 1 Goals of this Lecture Recall from last lecture Help you learn about: The decisions that were available to the designers of C The decisions that were

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

Advanced Computer Networks. Rab Nawaz Jadoon DCS. Assistant Professor COMSATS University, Lahore Pakistan. Department of Computer Science

Advanced Computer Networks. Rab Nawaz Jadoon DCS. Assistant Professor COMSATS University, Lahore Pakistan. Department of Computer Science Advanced Computer Networks Department of Computer Science DCS COMSATS Institute of Information Technology Rab Nawaz Jadoon Assistant Professor COMSATS University, Lahore Pakistan Advanced Computer Networks

More information

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

CS107, Lecture 3 Bits and Bytes; Bitwise Operators CS107, Lecture 3 Bits and Bytes; Bitwise Operators reading: Bryant & O Hallaron, Ch. 2.1 This document is copyright (C) Stanford Computer Science and Nick Troccoli, licensed under Creative Commons Attribution

More information

Chapter 4: Computer Codes. In this chapter you will learn about:

Chapter 4: Computer Codes. In this chapter you will learn about: Ref. Page Slide 1/30 Learning Objectives In this chapter you will learn about: Computer data Computer codes: representation of data in binary Most commonly used computer codes Collating sequence Ref. Page

More information

Reading and writing files

Reading and writing files C H A P T E R 1 3 Reading and writing files 131 Opening files and file objects 131 132 Closing files 132 133 Opening files in write or other modes 132 134 Functions to read and write text or binary data

More information

BLM2031 Structured Programming. Zeyneb KURT

BLM2031 Structured Programming. Zeyneb KURT BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help

More information

DM536 Programming A. Peter Schneider-Kamp.

DM536 Programming A. Peter Schneider-Kamp. DM536 Programming A Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm536/! PROJECT PART 1 2 Organizational Details 2 possible projects, each consisting of 2 parts for 1 st part,

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

A Little Python Part 3

A Little Python Part 3 A Little Python Part 3 Introducing Programming with Python I/O, Files, Object Classes, Exception Handling Outline I/O Files opening File I/O, reading writing Python Objects Defining a new object Inheritance

More information

Teaching London Computing

Teaching London Computing Teaching London Computing Programming for GCSE Topic 10.1: Files William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London Aims Be able to develop simple programs

More information

CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O

CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O Introduction The WRITE and READ ADT Operations Case Studies: Arrays Strings Binary Trees Binary Search Trees Unordered Search Trees Page 1 Introduction

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

LESSON 4. The DATA TYPE char

LESSON 4. The DATA TYPE char LESSON 4 This lesson introduces some of the basic ideas involved in character processing. The lesson discusses how characters are stored and manipulated by the C language, how characters can be treated

More information

Course Schedule. CS 221 Computer Architecture. Week 3: Plan. I. Hexadecimals and Character Representations. Hexadecimal Representation

Course Schedule. CS 221 Computer Architecture. Week 3: Plan. I. Hexadecimals and Character Representations. Hexadecimal Representation Course Schedule CS 221 Computer Architecture Week 3: Information Representation (2) Fall 2001 W1 Sep 11- Sep 14 Introduction W2 Sep 18- Sep 21 Information Representation (1) (Chapter 3) W3 Sep 25- Sep

More information

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline Python Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar December 28, 2011 1 Outline Introduction Installation and Use Distinct Features Python Basics Functional Example Comparisons with

More information

TABLE OF CONTENTS 2 CHAPTER 1 3 CHAPTER 2 4 CHAPTER 3 5 CHAPTER 4. Algorithm Design & Problem Solving. Data Representation.

TABLE OF CONTENTS 2 CHAPTER 1 3 CHAPTER 2 4 CHAPTER 3 5 CHAPTER 4. Algorithm Design & Problem Solving. Data Representation. 2 CHAPTER 1 Algorithm Design & Problem Solving 3 CHAPTER 2 Data Representation 4 CHAPTER 3 Programming 5 CHAPTER 4 Software Development TABLE OF CONTENTS 1. ALGORITHM DESIGN & PROBLEM-SOLVING Algorithm:

More information

EE 109 Unit 3. Analog vs. Digital. Analog vs. Digital. Binary Representation Systems ANALOG VS. DIGITAL

EE 109 Unit 3. Analog vs. Digital. Analog vs. Digital. Binary Representation Systems ANALOG VS. DIGITAL 3. 3. EE 9 Unit 3 Binary Representation Systems ANALOG VS. DIGITAL 3.3 3. Analog vs. Digital The analog world is based on continuous events. Observations can take on any (real) value. The digital world

More information

Shells and Shell Programming

Shells and Shell Programming Shells and Shell Programming 1 Shells A shell is a command line interpreter that is the interface between the user and the OS. The shell: analyzes each command determines what actions are to be performed

More information

l l l l l l l Base 2; each digit is 0 or 1 l Each bit in place i has value 2 i l Binary representation is used in computers

l l l l l l l Base 2; each digit is 0 or 1 l Each bit in place i has value 2 i l Binary representation is used in computers 198:211 Computer Architecture Topics: Lecture 8 (W5) Fall 2012 Data representation 2.1 and 2.2 of the book Floating point 2.4 of the book Computer Architecture What do computers do? Manipulate stored information

More information

Lecture 4: Basic I/O

Lecture 4: Basic I/O Lecture 4: Basic I/O CS1068+ Introductory Programming in Python Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (21/09/17) Lecture 4: Basic I/O 2017-2018 1 / 20

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information

Chapter 9: Working With Data

Chapter 9: Working With Data Chapter 9: Working With Data o Working with Data DML Component of SQL Used with much greater frequency than DDL Used to Add / Maintain / Delete / Query tables INSERT Used to enter new records o Data entry

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #8 Feb 27 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline More c Preprocessor Bitwise operations Character handling Math/random Review for midterm Reading: k&r ch

More information