Class 9 Reading and writing to files chr, ord and Unicode

Slides:



Advertisements
Similar presentations
Files CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Advertisements

Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Characters and Strings. Characters In Java, a char is a primitive type that can hold one single character A character can be: –A letter or digit –A punctuation.
INTRODUCTION TO PYTHON PART 4 – TEXT AND FILE PROCESSING CSC482 Introduction to Text Analytics Thomas Tiahrt, MA, PhD.
Topics This week: File input and output Python Programming, 2/e 1.
2.1.4 BINARY ASCII CHARACTER SETS A451: COMPUTER SYSTEMS AND PROGRAMMING.
Group practice in problem design and problem solving
Working with Files CSC 161: The Art of Programming Prof. Henry Kautz 11/9/2009.
Introduction to Computing Using Python Chapter 6  Encoding of String Characters  Randomness and Random Sampling.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
CATHERINE AND ANNIE Python: Part 4. Strings  Strings are interesting creatures. Although words are strings, anything contained within a set of quotes.
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Lecture 06 – Reading and Writing Text Files.  At the end of this lecture, students should be able to:  Read text files  Write text files  Example.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Course A201: Introduction to Programming 12/9/2010.
Files Victor Norman CS104. Reading Quiz, Q1 A file must be ___________ before a program can read data from it. A. accessed B. unlocked C. opened D. controlled.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Representing Characters in a computer Pressing a key on the computer a code is generated that the computer can convert into a symbol for displaying or.
Computing Science 1P Large Group Tutorial: Lab Exam & Class Test Simon Gay Department of Computing Science University of Glasgow 2006/07.
Files Tutor: You will need ….
Files in Python Output techniques. Outputting to a file There are two ways to do this in Python – print (more familiar, more flexible) – write (more restrictive)
Python – May 12 Recap lab Chapter 2 –operators –Strings –Lists –Control structures.
1 CSC 221: Introduction to Programming Fall 2011 Input & file processing  input vs. raw_input  files: input, output  opening & closing files  read(),
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
17-Mar-16 Characters and Strings. 2 Characters In Java, a char is a primitive type that can hold one single character A character can be: A letter or.
Python I/O Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Classic file reading 1 infile = open(’filename.txt’, ’r’) for line.
IIITD File Input / Output In Python. File and operations  File is a named location on disk to store related information  When we want to read from or.
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 Processing CMSC 120: Visualizing Information Lecture 4/15/08.
1.4 Representation of data in computer systems Character.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
By the end of this session you should be able to... Understand character sets and why these are used within computer systems. Understand how characters.
File Processing Upsorn Praphamontripong CS 1110
Binary Representation in Text
Binary Representation in Text
Topic: File Input/Output (I/O)
Module 5 Working with Data
CMSC201 Computer Science I for Majors Lecture 22 – Binary (and More)
CSc 110, Spring 2017 Lecture 18: Line-Based File Input
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CSc 120 Introduction to Computer Programing II
Python’s input and output
Data Encoding Characters.
File Handling Programming Guides.
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
File IO and Strings CIS 40 – Introduction to Programming in Python
Using files Taken from notes by Dr. Neil Moore
Intro to Computer Science CS1510
Presenting information as bit patterns
CS 1111 Introduction to Programming Fall 2018
Introduction to Python: Day Three
Digital Encodings.
Text / Serial / Sequential Files
Rocky K. C. Chang 30 October 2018 (Based on Zelle and Dierbach)
CS190/295 Programming in Python for Life Sciences: Lecture 3
functions: argument, return value
15-110: Principles of Computing
Topics Introduction to File Input and Output
CPS120: Introduction to Computer Science
CHAPTER 4: Lists, Tuples and Dictionaries
CS2911 Week 2, Class 3 Today Return Lab 2 and Quiz 1
CS2911 Week 3, Lab Today Thursday Friday Review Muddiest Point Lab 3
Topics Introduction to File Input and Output
Text / Serial / Sequential Files
CS 1111 Introduction to Programming Spring 2019
Introduction to Computer Science
Presentation transcript:

Class 9 Reading and writing to files chr, ord and Unicode functions without parameters or returns values

File Processing Working with text files in Python Associate a disk file with a file object using the open function <filevar> = open(<name>, <mode>) name is a string with the actual file name on the disk. The mode is either ‘r’ or ‘w’ depending on whether we are reading or writing the file. infile = open("numbers.dat", "r") outfile = open("results.txt", "w") Python Programming, 3/e

File processing input file – problem if not found output file – overwrites existing file

File Methods <file>.read() – returns the entire remaining contents of the file as a single (possibly large, multi-line) string <file>.readline() – returns the next line of the file. This is all text up to and including the next newline character <file>.readlines() – returns a list of the remaining lines in the file. Each list item is a single line including the newline characters. Python Programming, 3/e

File Processing Opening a file for writing prepares the file to receive data Don't forget to close! If you open an existing file for writing, you wipe out the file’s contents. If the named file does not exist, a new one is created. outfile = open("mydata.out", "w") print(<expressions>, file=outfile) Python Programming, 3/e

Some solutions to lab 8 and how they work (and their limitations.)

Lab8AWLv1.py #Lab8AWLv1 # get the input file name and open the file filename=input("Enter input file name: ") infile=open(filename,"r") # get the output file name and open the file filename=input("Enter the output file name: ") outfile=open(filename,"w") # read file using readlines, and print to screen saying=infile.readlines() print(saying) # for each line in the saying, # compute the average word length for line in saying: sum=0.0 count=0 for word in line.split(): print(word, end="-") sum=sum+len(word) count=count+1 print() #skip to next line #print the result print(line, file=outfile) print(sum, count, sum/count, file=outfile) infile.close() outfile.close()

Notes on solution readlines – what does it return? What is saying? What is line.split()? What is word? accumulating sum (of the number of letters) counting re-initialize for each line

Lab8AWLv1.py Can it handle any file of lines of text? Does it count the punctuation as letters? Does it count newlines as letters? Does the input file need a newline after the last line of text? Why the funny spacing?

Seasons.txt Seasons.txt Thirty days hath September April, June, and November All the rest have thirty-one Except February, which has twenty-eight.

SeasonsOut.txt Thirty days hath September 23.0 4 5.75 April, June, and November 22.0 4 5.5 All the rest have thirty-one 24.0 5 4.8 Except February, which has twenty-eight. 36.0 5 7.2

shell output ['Thirty days hath September\n', 'April, June, and November\n', 'All the rest have thirty-one\n', 'Except February, which has twenty-eight.'] Thirty-days-hath-September- April,-June,-and-November- All-the-rest-have-thirty-one- Except-February,-which-has-twenty-eight.-

fastAnimals.txt cat can run horses really gallop

fastAnimalsOut.txt cat can run 9.0 3 3.0 horses really gallop 18.0 3 6.0

fastAnimals shell output ['cat can run\n', 'horses really gallop'] cat-can-run- horses-really-gallop-

Lab8AWLv2.py #Lab8AWLv2 # get the input file name and open the file filename=input("Enter input file name: ") infile=open(filename,"r") # get the output file name and open the file filename=input("Enter the output file name: ") outfile=open(filename,"w") # read file using readline, and print to screen # for each line in the saying, # read the line from the file and # compute the average word length for k in range(4): line=infile.readline() print(line) sum=0.0 count=0 for word in line.split(): print(word, end="-") sum=sum+len(word) count=count+1 print() #skip to next line #print the result print(line, file=outfile) print(sum, count, sum/count, file=outfile) infile.close() outfile.close()

Lab8AWLv2.py Can it handle any file of lines of text? Does it count the punctuation as letters? Does it count newlines as letters? Does the input file need a newline after the last line of text? Why the funny spacing?

Lab8AWLv2.py Can it handle any file of lines of text? Must have 4 Does it count the punctuation as letters? Yes Does it count newlines as letters? No Does the input file need a newline after the last line of text? No Why the funny spacing? stores the newline

Lab8AWLv3.py #Lab8AWLv3 #print to the screen not to an output file # get the input file name and open the file filename=input("Enter input file name: ") infile=open(filename,"r") # read file using readlines, and print to screen saying=infile.readlines() print(saying) # for each line in the saying, # compute the average word length for line in saying: print(line) lineSplit=line.split() wordsJoin="".join(lineSplit) #the words #without spaces letterCount=len(wordsJoin) wordsCount=len(lineSplit) #length of a list avg=letterCount/wordsCount #print the result print(letterCount, wordsCount, avg) infile.close()

Coding and Encryption See discussion in the book

String Representation In the early days of computers, each manufacturer used their own encoding of numbers for characters. ASCII system (American Standard Code for Information Interchange) uses 127 bit codes Python supports Unicode (100,000+ characters) Python Programming, 3/e

String Representation The ord function returns the numeric (ordinal) code of a single character. The chr function converts a numeric code to the corresponding character. >>> ord("A") 65 >>> ord("a") 97 >>> chr(97) 'a' >>> chr(65) 'A' Python Programming, 3/e

Building a string accumulate a string First initialize it: message="" as we go through loop adding characters (or other strings): message= message + <string>

Lists Have Methods, Too The append method can be used to add an item at the end of a list. squares = [] for x in range(1,101): squares.append(x*x) We start with an empty list ([]) and each number from 1 to 100 is squared and appended to it ([1, 4, 9, …, 10000]). Python Programming, 3/e

Unicode str to convert a number into a string (so can concat, for exam) Not the same as chr!