Python I/O Peter Wad Sackett.

Slides:



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

Files CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
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.
Files in Python The Basics. Why use Files? Very small amounts of data – just hardcode them into the program A few pieces of data – ask the user to input.
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.
Topics This week: File input and output Python Programming, 2/e 1.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
CSC 107 – Programming For Science. Announcements  Lectures may not cover all material from book  Material that is most difficult or challenging is focus.
Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
H3D API Training  Part 3.1: Python – Quick overview.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
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.
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.
Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Department of Electrical and Computer Engineering Introduction to C++: Primitive Data Types, Libraries and Operations By Hector M Lugo-Cordero August 27,
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
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.
Python – May 12 Recap lab Chapter 2 –operators –Strings –Lists –Control structures.
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 Exceptions and bug handling Peter Wad Sackett.
Today… Strings: –String Methods Demo. Raising Exceptions. os Module Winter 2016CISC101 - Prof. McLeod1.
Python I/O Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Classic file reading 1 infile = open(’filename.txt’, ’r’) for line.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Python Simple file reading Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Simple Pythonic file reading Python has a special.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
FOP: While Loops.
String and Lists Dr. José M. Reyes Álamo.
How to python source: Web_Dev fan on pinterest.
Chapter 1.2 Introduction to C++ Programming
Module 5 Working with Data
File Writing Upsorn Praphamontripong CS 1110
CSc 120 Introduction to Computer Programing II
MATLAB DENC 2533 ECADD LAB 9.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Class 9 Reading and writing to files chr, ord and Unicode
More Selections BIS1523 – Lecture 9.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
File Handling Programming Guides.
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
File IO and Strings CIS 40 – Introduction to Programming in Python
Using files Taken from notes by Dr. Neil Moore
Fundamentals of Programming I Files
Python Stateful Parsing
String and Lists Dr. José M. Reyes Álamo.
CS 1111 Introduction to Programming Fall 2018
Introduction to Python: Day Three
Representation and Manipulation
Python – a HowTo Peter Wad Sackett and Henrike Zschach.
Python Lists and Sequences
Fundamentals of Functional Programming
CHAPTER 3: String And Numeric Data In Python
Topics Introduction to File Input and Output
Python Sets and Dictionaries
Introduction to Computer Science
Terminal-Based Programs
Another Example Problem
“Everything Else”.
Topics Introduction to File Input and Output
Python Simple file reading
CS 1111 Introduction to Programming Spring 2019
Introduction to Computer Science
Chapter 13 Control Structures
Presentation transcript:

Python I/O Peter Wad Sackett

Classic file reading 1 Files are opened and closed infile = open(’filename.txt’, ’r’) for line in infile: print(line) # doing something with the line infile.close() open opens the file ’filename.txt’ for reading; ’r’. The associated filehandle is here called infile, but can be anything. The for loop iterates through each line in the file. The variable is called line (appropiate), but can be anything. After reading the lines, the file is closed by calling the close method on the filehandle object. This is quite similar to file reading with the with statement.

Classic file reading 2 Alternative file reading infile = open(’filename.txt’, ’r’) line = infile.readline() while line != ””: print(line) # doing something with the line line = infile.readline() # getting the next line infile.close() By calling the method readline on the filehandle object, a line will be read and returned. If there are no more lines in the file to read the empty string will be returned. Notice that the lines contain a newline in the end. Warning: You use this method or the previous method, but NOT A MIX. NEVER use ”for line in infile:” together with ”infile.readline()”.

Classic file writing File writing # Opening the file outfile = open(’filename.txt’, ’w’) # Method 1: Using write method on the file handle outfile.write(”First line in the file\n”) # Method 2: Using print function print(”Second line in the file”, file=outfile) # Closing the file outfile.close() By calling the method write on the filehandle object, a string will be written to the file. One string will be written. It can be a constructed string like: ”I am ” + name + ”. Hello\n” Notice, if you want a newline, you must specify it. print can be used in a familiar way, if adding the file= You can append text to an already written file with file mode ’a’. You can also use the with statement for writing files.

Examples Doing a simpel copy of a text file # Opening the files infile = open(’original.txt’, ’r’) outfile = open(’copy.txt’, ’w’) # The copy work for line in infile: outfile.write(line) # Closing the files infile.close() outfile.close() Every string/line read is simply being written in its entirety to the output file – including newlines.

Python libraries Python has a lot of standard libraries The libraries has to be imported to be used import sys A library gives access to ”new” functions. For example the sys library gives access to an exit function (and lot of other stuff). sys.exit(1) # ends the program with exit code 1 A library function is called by libname.funcname()

The sys library: STDIN and STDOUT The STDIN and STDOUT filehandles can be imported import sys line = sys.stdin.readline() sys.stdout.write(”Output to stdout\n”) The sys library is big and has many interesting and important functions which have to do with the platform and even the hardware. Not many are useful for a beginner. Full documentation: https://docs.python.org/3/library/sys.html

The os library Miscellaneous operating system interfaces import os os.system(”ls -l”) The os library is bigger than sys. Contains many useful functions. Common functions are: mkdir, rmdir, chdir, rename, remove, chmod, system, getpid, getenv Lots of low level I/O functions. Requires fairly good understanding of computers and operating systems. Full documentation: https://docs.python.org/3/library/os.html

Standard math library Advanced math functions are imported from library import math squareroot2 = math.sqrt(2) Lots of mathematical functions. The more common are: sqrt, log, pow, cos, sin, tan, acos, asin, atan, ceil, floor, isinf, isnan. Has also some useful constants: pi, e. Full documentation: https://docs.python.org/3/library/math.html

Examples Doing a copy of a text file – special attention to STOP and ERROR lines # Importing libraies import sys # Opening the files infile = open(’original.txt’, ’r’) outfile = open(’copy.txt’, ’w’) # The copy work for line in infile: if line == ”STOP\n”: break if line == ”ERROR\n”: print(”Error found, stopping”) sys.exit(1) outfile.write(line) # Closing the files infile.close() outfile.close()

Strings and parts of them Strings are immutable objects. A string is a sequence, a data type that supports certain operations. # Finding the length of a string, a sequence operation mystring = ’0123456789’ stringlength = len(mystring) # extract a char at a specific position, sequence operation thechar = mystring[3] # extract a substring/slice, sequence operation substring = mystring[2:5] print(stringlength, thechar, substring) Output is: 10 3 234 Strings/sequences are zero-based, i.e. first position is 0. Strings have several useful string-only operations.

More with strings Starting from the end of the string with negative numbers print mystring[-1] # print last char print mystring[5:-1] # result 5678 print mystring[:-1] # everything but the last char print mystring[4:] # from position 4 and onward print mystring[8:100] # result 89 If you ask for more chars than actually are in a string, like the last statement, python will give you what it has. There is no error. If you start outside the string, there will be an error. Iteration over a string Printing a string, one char on each line. mystring = ’0123456789’ for i in range(len(mystring)): print(mystring[i]) for character in mystring: print(character)

Examples Is the word ’Red’ in the string? The idea is to define what word to look for and then check all substrings in the line. Set a flag (boolean value) if the word is seen. searchWord = ’Red’ line = ’Green YellowRed Blue Ultraviolet’ wordPresent = False for i in range(len(line)): if line[i:i+3] == searchWord: wordPresent = True if wordPresent: print(searchWord, ”is present in the line”) else: print(searchWord, ”is NOT present in the line”) A problem that may need solving in this code is, if the word we look for has to be a ”real stand-alone” word or it can be part of something else.