Using Files. Wrestling with Python Classes. Rob Miles

Size: px
Start display at page:

Download "Using Files. Wrestling with Python Classes. Rob Miles"

Transcription

1 Using Files Wrestling with Python Classes Rob Miles

2 Persisting Data At the moment the data in our programs is discarded when we exit the Python system Programs need a way of persisting data Python can store data using the file system of the computer This also means that Python programs can share data with other programs File Handling 2-Dec-14 Rob Miles 2

3 Writing into a file f=open('fred.txt',mode='w') f.write('line 1\n') f.write('line 2') f.close() These four lines of text create a file that contains two lines: Line 1 Line 2 File Handling 2-Dec-14 Rob Miles 3

4 Writing into a file f=open('fred.txt',mode='w') f.write('line 1\n') f.write('line 2') f.close() These four lines of text create a file that contains two lines: Line 1 Line 2 The variable f refers to a file stream that connects the program to a file File Handling 2-Dec-14 Rob Miles 4

5 Writing into a file f=open('fred.txt',mode='w') f.write('line 1\n') f.write('line 2') f.close() These four lines of text create a file that contains two lines: Line 1 Line 2 The file is called Fred.txt File Handling 2-Dec-14 Rob Miles 5

6 Writing into a file f=open('fred.txt',mode='w') f.write('line 1\n') f.write('line 2') f.close() These four lines of text create a file that contains two lines: Line 1 Line 2 This is the filename which includes a language extension marking the file as text File Handling 2-Dec-14 Rob Miles 6

7 Writing into a file f=open('fred.txt',mode='w') f.write('line 1\n') f.write('line 2') f.close() These four lines of text create a file that contains two lines: Line 1 Line 2 This request that the file be opened for writing r would mean reading File Handling 2-Dec-14 Rob Miles 7

8 Writing into a file f=open('fred.txt',mode='w') f.write('line 1\n') f.write('line 2') f.close() These four lines of text create a file that contains two lines: Line 1 Line 2 This character sequence means Take a New Line here File Handling 2-Dec-14 Rob Miles 8

9 Writing into a file f=open('fred.txt',mode='w') f.write('line 1\n') f.write('line 2') f.close() It is very important that the file is closed when the writing has finished This is the point at which the text is actually written into the file File Handling 2-Dec-14 Rob Miles 9

10 File Storage Locations File Handling 2-Dec-14 Rob Miles 10

11 File Write Location If you just give the name of the file it will be created in the location where the program is running This might be a Python system directory Your files will be very hard to find on the system Your program might not be permitted to write there File Handling 2-Dec-14 Rob Miles 11

12 Where files are stored The files are stored in different places depending on the system you are using Different computers have different places where the files are stored PCs and Macs store files in different ways This also depends on how the PC is configured Some systems will store files on the network File Handling 2-Dec-14 Rob Miles 12

13 The File Path f=open('c:/users/rob/test.txt',mode='w') The file path is a string of text that specifies where on the system the file is located This would put a file called test.txt in the folder for user rob File Handling 2-Dec-14 Rob Miles 13

14 The Drive letter f=open('c:/users/rob/test.txt',mode='w') This specifies the drive where the file is to be stored The drive is specified by a letter Drive c: is usually the main storage device in your computer Other disks may have different letters File Handling 2-Dec-14 Rob Miles 14

15 The File Path separator f=open('c:/users/rob/test.txt',mode='w') The / character separates each of the folders in the path to this file In Windows there is a folder that holds another folder for each user of the system The separator is different for systems File Handling 2-Dec-14 Rob Miles 15

16 The Files on the Disk This is where the file ends up in my home directory File Handling 2-Dec-14 Rob Miles 16

17 Reading from a File File Handling 2-Dec-14 Rob Miles 17

18 Reading from a file f=open('fred.txt',mode='r') line = f.readline() print(line) f.close() A file can be opened in read mode Each call of readline will fetch the next line of the file Again, you should close the file when finished File Handling 2-Dec-14 Rob Miles 18

19 Detecting the end a file x = f.readline() if len(x) == 0: print('end of file') A program can detect when the end of a file has been reached by checking for a line length of zero An empty line in a file will have a length of 1, the linefeed character File Handling 2-Dec-14 Rob Miles 19

20 Reading all the lines a file f=open('fred.txt',mode='r') for line in f: print(line) A file can be used as the source of a for loop iteration The content of the loop will then be performed for each of the lines in the file File Handling 2-Dec-14 Rob Miles 20

21 Line endings >>> f=open('fred.txt',mode='r') >>> a = f.readline() >>> a 'Line 1\n' When you read a line from a file you will get the line ending character in the string This can cause problems with printing as you will get a blank line after each line File Handling 2-Dec-14 Rob Miles 21

22 Stripping >>> a = a.strip() >>> a 'Line 1' All string variables provide some methods that can act on them and return the result The strip method removes non-printing characters from the start and the end of a string File Handling 2-Dec-14 Rob Miles 22

23 Writing Numbers score = 6 f.write(str(score)) When we write a number value to a file it must be converted into a string before it can be written When the value is read back the program will have to use the int function to convert the string back into a value File Handling 2-Dec-14 Rob Miles 23

24 Exceptions try: except: f=open('fred.txt',mode='r') line = f.readline() print(line) f.close() print("error reading from file") When you use files you should capture exceptions that may be raised File Handling 2-Dec-14 Rob Miles 24

25 Writing Structured Data File Handling 2-Dec-14 Rob Miles 25

26 Writing out structured data You often have to write out the contents of a list of items You can use foreach loop to work through each item in the list It is a good idea to write out the number of items in the list first File Handling 2-Dec-14 Rob Miles 26

27 Writing a list of golf rounds file = open(self.filename,"w") numofrounds = len(self.rounds) file.write(str(numofrounds)+'\n') for round in self.rounds: round.writetofile(file) file.close() This code writes out the golf rounds to a file File Handling 2-Dec-14 Rob Miles 27

28 Opening the file file = open(self.filename,"w") numofrounds = len(self.rounds) file.write(str(numofrounds)+'\n') for round in self.rounds: round.writetofile(file) file.close() This opens the file for output The name is a property of the round File Handling 2-Dec-14 Rob Miles 28

29 Getting the number to write file = open(self.filename,"w") numofrounds = len(self.rounds) file.write(str(numofrounds)+'\n') for round in self.rounds: round.writetofile(file) file.close() This gets the length of the list of rounds that are to be stored File Handling 2-Dec-14 Rob Miles 29

30 Saving the number being written file = open(self.filename,"w") numofrounds = len(self.rounds) file.write(str(numofrounds)+'\n') for round in self.rounds: round.writetofile(file) file.close() This writes the length out into the file File Handling 2-Dec-14 Rob Miles 30

31 Writing each round file = open(self.filename,"w") numofrounds = len(self.rounds) file.write(str(numofrounds)+'\n') for round in self.rounds: round.writetofile(file) file.close() This writes out each round Note that the round is able to write itself File Handling 2-Dec-14 Rob Miles 31

32 Closing the file file = open(self.filename,"w") numofrounds = len(self.rounds) file.write(str(numofrounds)+'\n') for round in self.rounds: round.writetofile(file) file.close() This closes the file File Handling 2-Dec-14 Rob Miles 32

33 Reading Structured Data File Handling 2-Dec-14 Rob Miles 33

34 Reading the rounds back file = open(self.filename,"r") numofrounds = int(file.readline()) for i in range(numofrounds): round = Round() round.readfromfile(file) self.rounds.append(round) file.close() The behaviour to read the rounds file back is very similar File Handling 2-Dec-14 Rob Miles 34

35 Open the file for reading file = open(self.filename,"r") numofrounds = int(file.readline()) for i in range(numofrounds): round = Round() round.readfromfile(file) self.rounds.append(round) file.close() Open the file for reading File Handling 2-Dec-14 Rob Miles 35

36 Find out how many rounds there are in the file file = open(self.filename,"r") numofrounds = int(file.readline()) for i in range(numofrounds): round = Round() round.readfromfile(file) self.rounds.append(round) file.close() Retrieve the number of lines that were written File Handling 2-Dec-14 Rob Miles 36

37 Read each round in turn file = open(self.filename,"r") numofrounds = int(file.readline()) for i in range(numofrounds): round = Round() round.readfromfile(file) self.rounds.append(round) file.close() Go round the loop once for each round File Handling 2-Dec-14 Rob Miles 37

38 Create an empty round file = open(self.filename,"r") numofrounds = int(file.readline()) for i in range(numofrounds): round = Round() round.readfromfile(file) self.rounds.append(round) file.close() Make an empty round File Handling 2-Dec-14 Rob Miles 38

39 Read the round from the file file = open(self.filename,"r") numofrounds = int(file.readline()) for i in range(numofrounds): round = Round() round.readfromfile(file) self.rounds.append(round) file.close() Get the round to read itself from the file File Handling 2-Dec-14 Rob Miles 39

40 Store the newly read round file = open(self.filename,"r") numofrounds = int(file.readline()) for i in range(numofrounds): round = Round() round.readfromfile(file) self.rounds.append(round) file.close() Put the new round on the end of the list File Handling 2-Dec-14 Rob Miles 40

41 Close the file file = open(self.filename,"r") numofrounds = int(file.readline()) for i in range(numofrounds): round = Round() round.readfromfile(file) self.rounds.append(round) file.close() Close the file when you have finished File Handling 2-Dec-14 Rob Miles 41

42 Using split to break up input text t = " " u = t.split() print(u) ['1', '2', '3', '4'] You can ask a string to split itself into a list of the items in it File Handling 2-Dec-14 Rob Miles 42

43 Using split to break up input text t = " " u = t.split() print(u) ['1', '2', '3', '4'] This is very useful if you are reading items from a file File Handling 2-Dec-14 Rob Miles 43

44 Using split to break up input text t = " " u = t.split() print(u) ['1', '2', '3', '4'] The items are split on any whitespace character File Handling 2-Dec-14 Rob Miles 44

45 Using split to break up input text t = " " u = t.split(' ') print(u) ['1', '2', '3', '4'] You can specify the character to split on if you like File Handling 2-Dec-14 Rob Miles 45

46 Save methods in objects File Handling 2-Dec-14 Rob Miles 46

47 Division of Purpose It is sensible to make the data classes responsible for saving and loading their own data That way, if the design of the data changes we only have to update the behaviours in the classes themselves File Handling 2-Dec-14 Rob Miles 47

48 Round Save Method def writetofile(self, file): try: for hole in self.scorecard: s = str(hole.par)+' '+str(hole.shots) file.write(s+'\n') except: print('error writing to file',file.name) This method saves a round to a file The file to save to is passed as a parameter File Handling 2-Dec-14 Rob Miles 48

49 Passing a file as a parameter def writetofile(self, file): try: for hole in self.scorecard: s = str(hole.par)+' '+str(hole.shots) file.write(s+'\n') except: print('error writing to file',file.name) The method does not open the file to save into The file has already been opened File Handling 2-Dec-14 Rob Miles 49

50 Passing a file as a parameter def writetofile(self, file): try: for hole in self.scorecard: s = str(hole.par)+' '+str(hole.shots) file.write(s+'\n') except: print('error writing to file',file.name) This will append the round information onto the end of an already open file File Handling 2-Dec-14 Rob Miles 50

51 Two items on one line def writetofile(self, file): try: for hole in self.scorecard: s = str(hole.par)+' '+str(hole.shots) file.write(s+'\n') except: print('error writing to file',file.name) The par and the shots values are written on the same line of the file The read method uses the split function File Handling 2-Dec-14 Rob Miles 51

52 Filename in error reports def writetofile(self, file): try: for hole in self.scorecard: s = str(hole.par)+' '+str(hole.shots) file.write(s+'\n') except: print('error writing to file',file.name) You can find out the name of a file that is being used File Handling 2-Dec-14 Rob Miles 52

53 Improving the golf club programs Warren has created worked solutions for the Golf club tasks 1-3 The customer for the program likes them very much They would like an additional behaviour to be added File Handling 2-Dec-14 Rob Miles 53

54 Saving/Loading Game Results The customer would like to be able to save the results of games (Task 2) The scores for each player and who won the game must the stored in a text file which can be loaded later You can use the save and load behaviours from Task 3 as a good place to look for ideas File Handling 2-Dec-14 Rob Miles 54

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

File Handling Programming 1 C# Programming. Rob Miles

File Handling Programming 1 C# Programming. Rob Miles 08101 Programming 1 C# Programming Rob Miles Files At the moment when our program stops all the data in it is destroyed We need a way of persisting data from our programs The way to do this is to use files

More information

examples from first year calculus (continued), file I/O, Benford s Law

examples from first year calculus (continued), file I/O, Benford s Law examples from first year calculus (continued), file I/O, Benford s Law Matt Valeriote 5 February 2018 Grid and Bisection methods to find a root Assume that f (x) is a continuous function on the real numbers.

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

Fundamentals of Programming (Python) File Processing. Sina Sajadmanesh Sharif University of Technology Fall 2017

Fundamentals of Programming (Python) File Processing. Sina Sajadmanesh Sharif University of Technology Fall 2017 Fundamentals of Programming (Python) File Processing Sina Sajadmanesh Sharif University of Technology Outline 1. Sources of Input 2. Files 3. Opening a File 4. Opening Modes 5. Closing a File 6. Writing

More information

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

Decorate, sort, undecorate pattern

Decorate, sort, undecorate pattern Decorate, sort, undecorate pattern In a previous example, we read a file that contained data about Words with Friends games between me and my sister. Suppose we want to read this data again, and this time

More information

Micropower Solutions Leaderboard. Example of Leaderboard Running.

Micropower Solutions Leaderboard. Example of Leaderboard Running. Micropower Solutions Leaderboard Example of Leaderboard Running. 1 The Competition Set up the daily competition/s as you would normally, in PowerGolf. Enter scores. Click on the Leaderboard button periodically.

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

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

Chapter 6. Files and Exceptions I

Chapter 6. Files and Exceptions I Chapter 6 Files and Exceptions I What is a file? a file is a collection of data that is stored on secondary storage like a disk or a thumb drive accessing a file means establishing a connection between

More information

University of Hull Department of Computer Science. Wrestling with Python Week 04 Using Lists

University of Hull Department of Computer Science. Wrestling with Python Week 04 Using Lists University of Hull Department of Computer Science Wrestling with Python Week 04 Using Lists Vsn. 1.0 Rob Miles 2013 Before you go onto this lab, please make sure that you have sorted out the Cinema Entry

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

Previously. Iteration. Date and time structures. Modularisation.

Previously. Iteration. Date and time structures. Modularisation. 2017 2018 Previously Iteration. Date and time structures. Modularisation. Today File handling. Reading and writing files. In order for a program to work with a file, the program must create a file object

More information

1 Fall 2017 CS 1110/1111 Exam 3

1 Fall 2017 CS 1110/1111 Exam 3 1 Fall 2017 CS 1110/1111 Exam 3 Bubble in your computing ID in the footer of this page. We use an optical scanner to read it, so fill in the bubbles darkly. If you have a shorter ID, leave some rows blank.

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

Sequence Types FEB

Sequence Types FEB Sequence Types FEB 23-25 2015 What we have not learned so far How to store, organize, and access large amounts of data? Examples: Read a sequence of million numbers and output these in sorted order. Read

More information

Level 3 Computing Year 2 Lecturer: Phil Smith

Level 3 Computing Year 2 Lecturer: Phil Smith Level 3 Computing Year 2 Lecturer: Phil Smith We looked at: Previously Reading and writing files. BTEC Level 3 Year 2 Unit 16 Procedural programming Now Now we will look at: Appending data to existing

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

CSC148 Fall 2017 Ramp Up Session Reference

CSC148 Fall 2017 Ramp Up Session Reference Short Python function/method descriptions: builtins : input([prompt]) -> str Read a string from standard input. The trailing newline is stripped. The prompt string, if given, is printed without a trailing

More information

CMSC 201 Spring 2016 Lab 08 Strings and File I/O

CMSC 201 Spring 2016 Lab 08 Strings and File I/O CMSC 201 Spring 2016 Lab 08 Strings and File I/O Assignment: Lab 08 Strings and File I/O Due Date: During discussion, April 4 th through April 7 th Value: 10 points Part 1: File Input Using files as input

More information

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

Fundamentals of Python: First Programs. Chapter 4: Text Files Fundamentals of Python: First Programs Chapter 4: Text Files Objectives After completing this section, you will be able to Open a text file for output and write strings or numbers to the file Open a text

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

Final Exam(sample), Fall, 2014

Final Exam(sample), Fall, 2014 Final Exam(sample), Fall, 2014 Date: Dec 4 th, 2014 Time: 1.25 hours (1.00 a.m. 2:15 p.m.) Total: 100 points + 20 bonus Problem 1 T/F 2 Choice 3 Output Points 16 16 48 4 Programming 20 5 Bonus 20 Total

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

THE AUSTRALIAN NATIONAL UNIVERSITY Final Examination November COMP1730 / COMP6730 Programming for Scientists

THE AUSTRALIAN NATIONAL UNIVERSITY Final Examination November COMP1730 / COMP6730 Programming for Scientists THE AUSTRALIAN NATIONAL UNIVERSITY Final Examination November 2016 COMP1730 / COMP6730 Programming for Scientists Study Period: 15 minutes Time Allowed: 3 hours Permitted Materials: One A4 page (1 sheet)

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

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

MULTIPLE CHOICE. Chapter Seven

MULTIPLE CHOICE. Chapter Seven Chapter Seven MULTIPLE CHOICE 1. Which of these is associated with a specific file and provides a way for the program to work with that file? a. Filename b. Extension c. File object d. File variable 2.

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

Python: Short Overview and Recap

Python: Short Overview and Recap Python: Short Overview and Recap Benjamin Roth CIS LMU Benjamin Roth (CIS LMU) Python: Short Overview and Recap 1 / 39 Data Types Object type Example creation Numbers (int, float) 123, 3.14 Strings this

More information

Python Mini Lessons last update: May 29, 2018

Python Mini Lessons last update: May 29, 2018 Python Mini Lessons last update: May 29, 2018 From http://www.onlineprogramminglessons.com These Python mini lessons will teach you all the Python Programming statements you need to know, so you can write

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

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

LECTURE 4 Python Basics Part 3

LECTURE 4 Python Basics Part 3 LECTURE 4 Python Basics Part 3 INPUT We ve already seen two useful functions for grabbing input from a user: raw_input() Asks the user for a string of input, and returns the string. If you provide an argument,

More information

CS 2316 Exam 4 Fall 2011

CS 2316 Exam 4 Fall 2011 CS 2316 Exam 4 Fall 2011 Name : Grading TA: Integrity: By taking this exam, you pledge that this is your work and you have neither given nor received inappropriate help during the taking of this exam in

More information

OPUS Drag and Drop Word Searches

OPUS Drag and Drop Word Searches OPUS Drag and Drop Word Searches Word searches are simple to produce in OPUS using hotspots, vectors, and drag and drop features. With a bit of thought this tutorial could also be adapted to make a word

More information

CS101 - Text Processing Lecture 8

CS101 - Text Processing Lecture 8 CS101 - Text Processing Lecture 8 School of Computing KAIST 1 / 16 Roadmap Last week we learned Data structures String Set Dictionary Image processing 2 / 16 Roadmap Last week we learned Data structures

More information

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries Chapter 1 Data types In this chapter you will: learn about data types learn about tuples, lists and dictionaries make a magic card trick app. Data types In Python Basics you were introduced to strings

More information

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ HANDLING TEXT FILES 2 Reading Files open files

More information

MEIN 50010: Python Flow Control

MEIN 50010: Python Flow Control : Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-11 Program Overview Program Code Block Statements Expressions Expressions & Statements An expression has

More information

FILE HANDLING AND EXCEPTIONS

FILE HANDLING AND EXCEPTIONS FILE HANDLING AND EXCEPTIONS INPUT We ve already seen how to use the input function for grabbing input from a user: input() >>> print(input('what is your name? ')) What is your name? Spongebob Spongebob

More information

Standard File Pointers

Standard File Pointers 1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf

More information

CME 193: Introduction to Scientific Python Lecture 4: File I/O and Classes

CME 193: Introduction to Scientific Python Lecture 4: File I/O and Classes CME 193: Introduction to Scientific Python Lecture 4: File I/O and Classes Sven Schmit stanford.edu/~schmit/cme193 4: File I/O and Classes 4-1 Feedback form Please take a moment to fill out feedback form

More information

Slide Set 15 (Complete)

Slide Set 15 (Complete) Slide Set 15 (Complete) for ENCM 339 Fall 2017 Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary November 2017 ENCM 339 Fall 2017

More information

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013 Expressions and Casting C# Programming Rob Miles Data Manipulation We know that programs use data storage (variables) to hold values and statements to process the data The statements are obeyed in sequence

More information

Preview from Notesale.co.uk Page 2 of 79

Preview from Notesale.co.uk Page 2 of 79 COMPUTER PROGRAMMING TUTORIAL by tutorialspoint.com Page 2 of 79 tutorialspoint.com i CHAPTER 3 Programming - Environment Though Environment Setup is not an element of any Programming Language, it is the

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

Expressions and Casting

Expressions and Casting Expressions and Casting C# Programming Rob Miles Data Manipulation We know that programs use data storage (variables) to hold values and statements to process the data The statements are obeyed in sequence

More information

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2011 Python Python was developed

More information

Your Name: Your TA's Name: 1 / 10 CS 1301 CS1 with Robots Fall 2008 Exam 3

Your Name: Your TA's Name: 1 / 10 CS 1301 CS1 with Robots Fall 2008 Exam 3 1 / 10 CS 1301 CS1 with Robots Fall 2008 Exam 3 This test has ten (10) problems on Nine (9) pages. Some problems have multiple parts. Problem Score Possible Points 1. Vocabulary 15 2. Fill in the Blank

More information

Begin to code with Python Obtaining MTA qualification expanded notes

Begin to code with Python Obtaining MTA qualification expanded notes Begin to code with Python Obtaining MTA qualification expanded notes The Microsoft Certified Professional program lets you obtain recognition for your skills. Passing the exam 98-381, "Introduction to

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

[SCPY204] Computer Programing. for Physicists. Class 07: 23 Feb Content: File I/O, data visualization. Instructor: Puwis Amatyakul

[SCPY204] Computer Programing. for Physicists. Class 07: 23 Feb Content: File I/O, data visualization. Instructor: Puwis Amatyakul Computer Programing Class 07: 23 Feb 2017 Content: File I/O, data visualization [SCPY204] for Physicists Instructor: Puwis Amatyakul FEB 23 2017 Happy Thursday No quiz today! But, there are things I want

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

Converting File Input

Converting File Input Converting File Input As with the input func.on, the readline() method can only return strings If the file contains numerical data, the strings must be converted to the numerical value using the int()

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

ENGG1811 Computing for Engineers Week 9A: File handling

ENGG1811 Computing for Engineers Week 9A: File handling ENGG1811 Computing for Engineers Week 9A: File handling ENGG1811 UNSW, CRICOS Provider No: 00098G1 W9 slide 1 Motivations As an engineer, you may work with data Sometimes these data come in data files

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

CPSC 217 Assignment 3

CPSC 217 Assignment 3 CPSC 217 Assignment 3 Due: Monday November 23, 2015 at 12:00 noon Weight: 7% Sample Solution Length: 135 lines, including some comments (not including the provided code) Individual Work: All assignments

More information

P1322 Operator s Manual

P1322 Operator s Manual P1322 Operator s Manual BadgerWare, LLC PO Box 292 Dayton, OH 45409 877.298.3759 www.badgerware.net Table of Contents Section 1: Introduction...1 Section 2: P1322 Main Window...2 Section 3: Configure COM

More information

CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review

CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review File processing Files are opened with the open() command. We can open files for reading or writing. The open() command takes two arguments, the file name

More information

CSCA20 Worksheet Working with Files

CSCA20 Worksheet Working with Files CSCA20 Worksheet Working with Files 1 Philosophical question: what s a file? Q. A general answer? Q. A programmer s answer? 2 Opening and closing a file To start using a file, given its filename, you have

More information

(edit 3/7: fixed a typo in project specification 2-f) user_id that user enters should be in the range [0,n-1] (i.e., from 0 to n-1, inclusive))

(edit 3/7: fixed a typo in project specification 2-f) user_id that user enters should be in the range [0,n-1] (i.e., from 0 to n-1, inclusive)) CSE 231 Spring 2017 Programming Project 7 (edit 3/1: fixed a typo in num_in_common_between_lists(user1_friend_lst, user2_friend_lst as described in c) calc_similarity_scores(network)) (edit 3/7: fixed

More information

LynxPad 3.0 Quick Start Guide

LynxPad 3.0 Quick Start Guide LynxPad 3.0 Quick Start Guide This guide teaches you how to perform basic functions in LynxPad while managing your next competition. For help while using LynxPad, click Help from the Menu bar and click

More information

CSCE 110 Programming I

CSCE 110 Programming I CSCE 110 Programming I Basics of Python (Part 1): Variables, Expressions, and Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2013 Tiffani

More information

Previously. Iteration. Date and time structures. Modularisation.

Previously. Iteration. Date and time structures. Modularisation. Lecture 7 Previously Iteration. Date and time structures. Modularisation. Today Pseudo code. File handling. Pseudo code Pseudocode is an informal high-level description of the operating principle of a

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

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

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

More Lists, File Input, and Text Processing

More Lists, File Input, and Text Processing More Lists, File Input, and Text Processing 01204111 Computers and Programming Chaiporn Jaikaeo Department of Computer Engineering Kasetsart University Cliparts are taken from http://openclipart.org Revised

More information

Introduction to programming using Python

Introduction to programming using Python Introduction to programming using Python Matthieu Choplin matthieu.choplin@city.ac.uk http://moodle.city.ac.uk/ Session 6-2 1 Objectives To open a file, read/write data from/to a file To use file dialogs

More information

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points) Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow

More information

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science DECEMBER 2013 EXAMINATIONS CSC 108 H1F Instructors: Craig and Gries Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number:

More information

Lecture 8: Simple Calculator Application

Lecture 8: Simple Calculator Application Lecture 8: Simple Calculator Application Postfix Calculator Dr Kieran T. Herley Department of Computer Science University College Cork 2016/17 KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17

More information

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical Recommended Readings Chapter 5 Topic 5: Repetition Are you saying that I am redundant? That I repeat myself? That I say the same thing over and over again? 1 2 Repetition So far, we have learned How to

More information

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program: Question 1. Part (a) [4 marks] Consider this program: [13 marks] def square(x): (number) -> number Write what this program prints, one line per box. There are more boxes than you need; leave unused ones

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/58 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

CPSC 217 Assignment 3

CPSC 217 Assignment 3 CPSC 217 Assignment 3 Due: Monday November 26, 2018 at 12:00 noon Weight: 7% Sample Solution Length: Approximately 120 lines, including blank lines, lots of comments and the provided code Individual Work:

More information

PHY Microprocessor Interfacing Techniques LabVIEW Tutorial - Part X File Output and Input

PHY Microprocessor Interfacing Techniques LabVIEW Tutorial - Part X File Output and Input PHY 406 - Microprocessor Interfacing Techniques LabVIEW Tutorial - Part X File Output and Input Introduction File I/O tends to be complex - simply because there are a myriad of things that you might want

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

COMP Streams and File I/O. Yi Hong June 10, 2015

COMP Streams and File I/O. Yi Hong June 10, 2015 COMP 110-001 Streams and File I/O Yi Hong June 10, 2015 Today Files, Directories, Path Streams Reading from a file Writing to a file Why Use Files for I/O? RAM is not persistent Data in a file remains

More information

Spring 2008 June 2, 2008 Section Solution: Python

Spring 2008 June 2, 2008 Section Solution: Python CS107 Handout 39S Spring 2008 June 2, 2008 Section Solution: Python Solution 1: Jane Austen s Favorite Word Project Gutenberg is an open-source effort intended to legally distribute electronic copies of

More information

An Introduction to Python for KS4!

An Introduction to Python for KS4! An Introduction to Python for KS4 Python is a modern, typed language - quick to create programs and easily scalable from small, simple programs to those as complex as GoogleApps. IDLE is the editor that

More information

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function Files Files File I/O Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function open(file, mode='r', buffering=-1, encoding=none,...

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

TENSOR TOOL USER S MANUAL

TENSOR TOOL USER S MANUAL TENSOR TOOL USER S MANUAL Table of Contents Introduction............................................ 1 Document Layout........................................ 1 Starting TTool..........................................

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Python Lab 9: Functions PythonLab9 lecture slides.ppt 27 November 2018 Ping Brennan (p.brennan@bbk.ac.uk) 1 Getting Started Create a new folder in your disk space with the name

More information

Lab 1: Silver Dollar Game 1 CSCI 2101B Fall 2018

Lab 1: Silver Dollar Game 1 CSCI 2101B Fall 2018 Lab 1: Silver Dollar Game 1 CSCI 2101B Fall 2018 Due: Tuesday, September 18, 11:59 pm Collaboration Policy: Level 1 (review full policy for details) Group Policy: Individual This lab will give you experience

More information

Chapter 18: Persistence

Chapter 18: Persistence Chapter 18: Persistence This chapter introduces persistent data and methods for storing information in a file and database. You'll learn the basics of SQL and how App Engine lets you use objects to store

More information

CMSC 201 Fall 2016 Lab 13 More Recursion

CMSC 201 Fall 2016 Lab 13 More Recursion CMSC 201 Fall 2016 Lab 13 More Recursion Assignment: Lab 13 More Recursion Due Date: During discussion, December 5th through 8th Value: 10 points Part 1A: What is Recursion? So far this semester, we ve

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

CS-141 Exam 2 Review November 10, 2017 Presented by the RIT Computer Science Community

CS-141 Exam 2 Review November 10, 2017 Presented by the RIT Computer Science Community CS-141 Exam 2 Review November 10, 2017 Presented by the RIT Computer Science Community http://csc.cs.rit.edu Linked Lists 1. You are given the linked sequence: 1 2 3. You may assume that each node has

More information

CME 193: Introduction to Scientific Python Lecture 4: Strings and File I/O

CME 193: Introduction to Scientific Python Lecture 4: Strings and File I/O CME 193: Introduction to Scientific Python Lecture 4: Strings and File I/O Nolan Skochdopole stanford.edu/class/cme193 4: Strings and File I/O 4-1 Contents Strings File I/O Classes Exercises 4: Strings

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

KNOWLEDGE FORUM 4 MACINTOSH SERVER ADMINISTRATOR S GUIDE

KNOWLEDGE FORUM 4 MACINTOSH SERVER ADMINISTRATOR S GUIDE KNOWLEDGE FORUM 4 MACINTOSH SERVER ADMINISTRATOR S GUIDE Knowledge Forum is a registered trademark of Knowledge Building Concepts. Administrator s Guide Macintosh Server--Version 4.1 or above Macintosh

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Python Lab 7: if Statement PythonLab7 lecture slides.ppt 14 November 2017 Ping Brennan (p.brennan@bbk.ac.uk) 1 Getting Started Create a new folder in your disk space with the

More information

CMSC 201 Fall 2017 Lab 12 File I/O

CMSC 201 Fall 2017 Lab 12 File I/O CMSC 201 Fall 2017 Lab 12 File I/O Assignment: Lab 12 File I/O Due Date: During discussion, November 27th through November 30th Value: 10 points (8 points during lab, 2 points for Pre Lab quiz) This week

More information

Homework 1. Hadachi&Lind October 25, Deadline for doing homework is 3 weeks starting from now due date is:

Homework 1. Hadachi&Lind October 25, Deadline for doing homework is 3 weeks starting from now due date is: Homework 1 Hadachi&Lind October 25, 2017 Must Read: 1. Deadline for doing homework is 3 weeks starting from now 2017.10.25 due date is: 2017.11.15 5:59:59 EET 2. For any delay in submitting the homework

More information

An Introduction to Python

An Introduction to Python An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many

More information