How to read from a file read, readline, reader

Slides:



Advertisements
Similar presentations
Computer Science 111 Fundamentals of Programming I Files.
Advertisements

Last Week Looping though lists Looping using range While loops.
Files CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Lists Introduction to Computing Science and Programming I.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
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.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
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.
ISU Basic SAS commands Laboratory No. 1 Computer Techniques for Biological Research Animal Science 500 Ken Stalder, Professor Department of Animal Science.
CIT 590 Intro to Programming Files etc. Announcements From HW5 onwards (HW5, HW6,…) You can work alone. You can pick your own partner. You can also stick.
5 1 Data Files CGI/Perl Programming By Diane Zak.
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.
COMP 116: Introduction to Scientific Programming Lecture 29: File I/O.
Files Tutor: You will need ….
Last Week Lists List methods Nested Lists Looping through lists using for loops.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
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])
CIT 590 Intro to Programming Files etc. Agenda Files Try catch except A module to read html off a remote website (only works sometimes)
CSV Files Intro to Computer Science CS1510 Dr. Sarah Diesburg.
CIT 590 Intro to Programming Lecture 6. Vote in the doodle poll so we can use some fancy algorithm to pair you up You.
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.
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()
Learning to use a ‘For Loop’ and a ‘Variable’. Learning Objective To use a ‘For’ loop to build shapes within your program Use a variable to detect input.
Emdeon Office Batch Management Services This document provides detailed information on Batch Import Services and other Batch features.
Prof. Katherine Gibson Prof. Jeremy Dixon
Introduction to C Topics Compilation Using the gcc Compiler
Topic: File Input/Output (I/O)
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Variables, Expressions, and IO
Handling errors try except
Engineering Innovation Center
Exceptions and files Taken from notes by Dr. Neil Moore
ECONOMETRICS ii – spring 2018
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Python I/O.
File Handling Programming Guides.
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Number and String Operations
Introduction to Programming with Python
File IO and Strings CIS 40 – Introduction to Programming in Python
Displaying text print Susan Ibach | Technical Evangelist
Fundamentals of Programming I Files
Learning Outcomes –Lesson 4
Exceptions and files Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
Introduction to Programming using Python
Coding Concepts (Data Structures)
Fundamentals of Data Structures
Loops CIS 40 – Introduction to Programming in Python
Remembering lists of values lists
Introduction to Python: Day Three
Text / Serial / Sequential Files
Functions Christopher Harrison | Content Developer
How to save information in files open, write, close
15-110: Principles of Computing
Topics Introduction to File Input and Output
BO65: PROGRAMMING WRITING TO TEXT FILES.
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
Making decisions with code
Python 3 Mr. Husch.
Topics Introduction to File Input and Output
Text / Serial / Sequential Files
Introduction to Computer Science
Working with dates and times
Presentation transcript:

How to read from a file read, readline, reader Susan Ibach | Technical Evangelist Christopher Harrison | Content Developer

Writing something down to remember it is only helpful if you can read it when you need it later! Reading a shopping list at the grocery store so you know what to buy Checking the number of guests on a guest list so you can see if you have enough food Looking up a phone number so you can call someone

In programs we often have to read information that was saved in files When you start your e-book reader, it looks up what page you were on when you last shut down When you start up your game, it looks up what treasures you had already collected so you can pick up where you left off There all also thousands of interesting OpenData files out there you can read to find out cool information you can use in your programs. For example: you can find out what fauna they have at the museum in Tasmania (You would be amazed at the data files you can find on the internet!)

Text files

How do we read a file with code? Use the open function myFile = open(fileName, accessMode) Look familiar? Yes, it’s the same method we use to write to a file So how does the program know whether to read or write? The access mode Access mode Action r Read the file w Write to the file a Append to the existing file content b Open a binary file

How do you read the file contents? Use the read method fileContent= myFile.read() The read method will return the entire contents of the file into the specified string variable

If you prefer you can read one line at a time Use the readline method fileContent= myFile.readline() The readline method will return one line from the file

Read a file

CSV files

If you are reading a CSV file, there is a csv library that will help you! To access the features in the csv library you must import it import csv

Now you can use the reader function to return all the rows from the file into a list The reader function will take an open csv file and return each row from the file into a list dataFromFile = csv.reader(myCSVfile) If your file is not using a comma to separate the values, you can tell the reader function what character is used as a delimiter dataFromFile = csv.reader(myCSVFile, delimiter=",")

Now we can open and read a csv file fileName = "GuestList.txt“ accessMode = "r" with open(fileName, accessMode) as myCSVFile:      #Read the file contents dataFromFile = csv.reader(myCSVFile)

Why do we have a ‘with’ and ‘:’ ? with open(fileName, accessMode) as myCSVFile: Programs should always open a file, and close it when they are done If they don’t sometimes the code crashes when you try to re- open a file that wasn’t closed last time you ran your code The ‘with’ ‘:’ syntax is used for certain methods to make sure clean up code such as close file runs even if there is an error.

Once we have all the rows from the csv files returned, how do we access the individual rows? Use a for loop to loop through the values in the list Each row will be one value with open(fileName, accessMode) as myCSVFile: #Read the file contents dataFromFile = csv.reader(myCSVFile) #For loop that will run once per row for row in dataFromFile :         print(row)

Put it all together and it looks something like this fileName = "GuestList.txt" accessMode = "r" with open(fileName, accessMode) as myCSVFile: #Read the file contents dataFromFile = csv.reader(myCSVFile) #For loop that will run #once per row for row in dataFromFile :         print(row)

Read a CSV file

What if I want to access an individual value from a row and not just print the whole row? The row returned in the loop is actually a list of the words in that row for row in dataFromFile :        print(row) for value in row :             print(value + "\n") So you can just create a nested loop to loop through the words in the row

But I don’t like those square brackets and quotes it added to the rows! You can use the join function to format the output SeparatorToDisplay.join(myList) for row in dataFromFile :           print (', '.join(row))

Reading individual values from a CSV file

Your challenge Write a program that will print the names and ages of the guests in the guest list file you created in the last module If you didn’t do the last challenge, you can just create a file to read using Notepad that contains names and ages

Congratulations You can now write a program that can receive or retrieve information from a file!