Files Tutor: You will need ….

Slides:



Advertisements
Similar presentations
Flow Charts, Loop Structures
Advertisements

File Handling Advanced Higher Programming. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a.
Alford Academy Business Education and Computing1 Advanced Higher Computing Based on Heriot-Watt University Scholar Materials File Handling.
Files Introduction to Computing Science and Programming I.
Understanding the Mainline Logical Flow Through a Program (continued)
Files in Python Input techniques. Input from a file The type of data you will get from a file is always string or a list of strings. There are two ways.
MIS316 – BUSINESS APPLICATION DEVELOPMENT – Chapter 14 – Files and Streams 1Microsoft Visual C# 2012, Fifth Edition.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Group practice in problem design and problem solving
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Topics Introduction Hardware and Software How Computers Store Data
Introduction to Python
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
General Programming Introduction to Computing Science and Programming I.
Python File Handling. In all the programs you have made so far when program is closed all the data is lost, but what if you want to keep the data to use.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Programming Fundamentals. Today’s Lecture Why do we need Object Oriented Language C++ and C Basics of a typical C++ Environment Basic Program Construction.
ISU Basic SAS commands Laboratory No. 1 Computer Techniques for Biological Research Animal Science 500 Ken Stalder, Professor Department of Animal Science.
Term 2, 2011 Week 1. CONTENTS Problem-solving methodology Programming and scripting languages – Programming languages Programming languages – Scripting.
Chapter 14: Files and Streams. 2Microsoft Visual C# 2012, Fifth Edition Files and the File and Directory Classes Temporary storage – Usually called computer.
Using Text Files in Excel File I/O Methods. Working With Text Files A file can be accessed in any of three ways: –Sequential access: By far the most common.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Lecture 6: Output 1.Presenting results in a professional manner 2.semicolon, disp(), fprintf() 3.Placeholders 4.Special characters 5.Format-modifiers 1.
File Systems cs550 Operating Systems David Monismith.
Python Let’s get started!.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
1 CSC 221: Introduction to Programming Fall 2011 Input & file processing  input vs. raw_input  files: input, output  opening & closing files  read(),
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
Python Lesson 1 1. Starter Create the following Excel spreadsheet and complete the calculations using formulae: 2 Add A1 and B1 A2 minus B2 A3 times B3.
Files A collection of related data treated as a unit. Two types Text
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
NXT File System Just like we’re able to store multiple programs and sound files to the NXT, we can store text files that contain information we specify.
Python: File Directories What is a directory? A hierarchical file system that contains folders and files. Directory (root folder) Sub-directory (folder.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 10: Files.
Part 1 Learning Objectives To understand that variables are a temporary named location to store data and that programmers work with different data types.
FILE I/O: Low-level 1. The Big Picture 2 Low-Level, cont. Some files are mixed format that are not readable by high- level functions such as xlsread()
Introduction to Computing Science and Programming I
Topic: File Input/Output (I/O)
Fundamentals of Python: First Programs
Introduction to Computing Science and Programming I
Chapter 13: File Input and Output
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Python I/O.
File Handling Programming Guides.
Topics Introduction to File Input and Output
Introduction to C++ Programming
File IO and Strings CIS 40 – Introduction to Programming in Python
Using files Taken from notes by Dr. Neil Moore
Fundamentals of Data Structures
Introduction to C++ Programming
Python programming exercise
Files Handling In today’s lesson we will look at:
15-110: Principles of Computing
Topics Introduction to File Input and Output
Introduction to Computer Science
Topics Introduction to File Input and Output
How to read from a file read, readline, reader
Introduction to Computer Science
Introduction to Computer Science
Presentation transcript:

Files Tutor: You will need …

Volatile and Non-Volatile Storage So far we have stored data using variables These variables are held in the computer’s volatile memory or RAM; when you close Python, your data is deleted We can also hold data in non-volatile files on a hard disk or USB stick These data files are not deleted when you close Python Files.pptx

File Types There are two different file types: Text Files Binary Files Human-readable Strings are sent to disk files They can be opened with programs like Notepad They are useful for simple, unstructured data They are larger than binary files because they store whitespace Binary Files Not directly human-readable Take up less space Not usually portable between programming languages Can be used to store more complex data Files.pptx

Writing To a Text File First, you must open the file: The file handle is a variable representing a stream to a disk file The file name can have any extension but .txt is conventional for text files The mode tells Python how you want to interact with the file. The wt mode means open a text file for writing Not specifying a path indicates that the file is in the same directory as the program file handle path file name mode Files.pptx

Writing to a Text File Now you can write string(s) to the file: You must include a newline character at the end of each line to separate them Finally, you should close the file: This flushes the stream and closes your connection to the file Files.pptx

Try This… You might need to change the path to somewhere you can write to or leave it off completely. When you have run this program, find the file and open it with Notepad Files.pptx

Reading from a Text File First you must open the file in read mode: Then you can read the file, line by line: The readline() function returns the next line from the file and it is stored in the ‘data’ variable Why is the end = “” used here? Files.pptx

Try This… Add this to your code Files.pptx

How many lines? Did you notice that we had two readline() statements? We need one readline() for each line in the file. What if the file has many lines or we don’t know how many lines there are? We can use an iterator, just like we did with sequences… Files.pptx

Appending… If you open an existing file in write mode, it will be deleted! You can open it in append mode if you want to avoid this… The new lines are added at the end If the files doesn’t already exist, it will be created Files.pptx

Exercise Write a program which asks the user to enter a series of sentences and writes them to a file. Allow an empty input to indicate that the user has finished. Once you have checked this is working correctly, add code which reads back all the data from the file and displays it on the screen. Files.pptx

Exercise Solution Part 1 Write the code which allows the user to enter sentences and stop when they enter a blank Files.pptx

Exercise Solution Part 2 Add in the file handling Find the file and make sure it contains the sentences you entered Files.pptx

Exercise Solution Part 3 Ensure the blank line isn’t written to the file Files.pptx

Exercise Solution Part 4 Read the sentences and display them Files.pptx

Comma Separated Files Comma Separated (CSV) file are a standard way of storing text data. E.g. name,email,phone Fred,fred@fred.com,0208-12901234 Sue,sue@sue.com,01727-837172 Fields are separated by commas Records are separated by line breaks There is an optional field name list on the first line You could open this using Excel and get a spreadsheet

CSV Files and Multi-Dimensional Lists How could a CSV file relate to a multi-dimensional list? Have a look at the previous CSV example again: name,email,phone Fred,fred@fred.com,0208-12901234 Sue,sue@sue.com,01727-837172 List of data labels List of lists… a multi-dimensional list Lists Files.pptx

CSV Files and Multi-Dimensional Lists Each record is a list holding data for one friend, e.g. The whole file is a multi-dimensional list e.g.

How could we create the CSV File? How could we write a CSV file for this multi-dimensional list? Each line in the file could represent a list, e.g. a friend But we can’t directly write a list to a file, e.g. Files.pptx

How could we do this? We could try converting the list to a string, e.g. That seems to work but what did it actually write? ['Fred', 'fred@fred.com', '0208-12901234'] When we read it back we would have to: remove the quotes split the line at the commas remove the square brackets manually create a list from it. This is possible but there is an easier way Files.pptx

The csv Module - Writing The csv module does all of this for you First open a file for writing as usual: Create a csv writer: Iterate over your data list and write each list: * use the option for any csv files to allow Python to handle the rows and newlines *

Exercise: Writing to a CSV File Download the file called highScores.py program from the VLE Add some code at the end of the program which writes the high scores list to a file called scores.txt Files.pptx

Exercise Solution Files.pptx

The csv Module - Reading First open a csvfile for reading as usual: Create a csv reader: Iterate over the csv_reader object and display: Or append the row (list) to the friends list: Files.pptx

Exercise: Reading from a CSV File Write a new program which reads the data from scores.txt and outputs it in the following format: <name> scored <score> in <game> Files.pptx

Exercise Solution Files.pptx

File Offsets When you read a line from a file, a pointer moves to the next line to be read Fred,Game 1,3049 John,Game 2,3943 If you want to move to the beginning of the file again then you must specifically move the file pointer next line pointer Files.pptx

File Offsets Files.pptx

File Access in Pseudo Code create new_scores array open csv text file for reading WHILE (NOT end of file) read next line from file append line to new_scores array END WHILE Files.pptx

File Access using a Flowchart Files.pptx