Programming: Input and Output in Python Bruce Beckles University of Cambridge Computing Service Day One.

Slides:



Advertisements
Similar presentations
Lab III – Linux at UMBC.
Advertisements

Linux+ Guide to Linux Certification, Second Edition
Linux+ Guide to Linux Certification, Second Edition
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
Computer Science A 1: 3/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
Introduction to Python. What is Python? Interpreted object oriented high level programming language – No compiling or linking neccesary Extensible: add.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Python Programming Fundamentals
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Introduction to Shell Script Programming
Introduction to Perl Practical Extraction and Report Language or Pathologically Eclectic Rubbish Lister or …
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
A Guide to Unix Using Linux Fourth Edition
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Functions Reading/writing files Catching exceptions
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Computer Science 101 Introduction to Programming.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Built-in Data Structures in Python An Introduction.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Lesson 3-Touring Utilities and System Features. Overview Employing fundamental utilities. Linux terminal sessions. Managing input and output. Using special.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
Lecture 4 Python Basics Part 3.
Linux+ Guide to Linux Certification, Second Edition Chapter 4 Exploring Linux Filesystems.
Lesson 6-Using Utilities to Accomplish Complex Tasks.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Today… Strings: –String Methods Demo. Raising Exceptions. os Module Winter 2016CISC101 - Prof. McLeod1.
PROGRAMMING USING PYTHON LANGUAGE ASSIGNMENT 1. INSTALLATION OF RASPBERRY NOOB First prepare the SD card provided in the kit by loading an Operating System.
Linux Administration Working with the BASH Shell.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Python: Further Topics Bruce Beckles University of Cambridge Computing Service Day One.
Python: Further Topics Bruce Beckles University of Cambridge Computing Service Day Two.
1 Support for Scientific Computing People: Bruce Beckles Nick Maclaren Services: Courses Advice.
Chapter 13 Debugging Strategies Learning by debugging.
Introduction to python programming
Lesson 5-Exploring Utilities
Introduction to Python
Embedded Software Development with Python and the Raspberry Pi
Introduction to Python
Variables, Expressions, and IO
Specification-Based Testing and the Category-Partition Method
Functions CIS 40 – Introduction to Programming in Python
CSE 303 Concepts and Tools for Software Development
CMSC201 Computer Science I for Majors Lecture 03 – Operators
Introduction to Python
Wordcount CSCE 587 Spring 2018.
Files I/O, Streams, I/O Redirection, Reading with fscanf
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Wordcount CSCE 587 Spring 2018.
Learning Outcomes –Lesson 4
Python Lessons 13 & 14 Mr. Kalmes.
Chapter Four UNIX File Processing.
(Oops! When things go wrong)
Introduction to Python: Day Three
Advanced Python Concepts: Exceptions
CSE 303 Concepts and Tools for Software Development
Advanced Python Concepts: Exceptions
Chapter 1: Programming Basics, Python History and Program Components
Input and Output Python3 Beginner #3.
General Computer Science for Engineers CISC 106 Lecture 03
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Topics Introduction to File Input and Output
Presentation transcript:

Programming: Input and Output in Python Bruce Beckles University of Cambridge Computing Service Day One

2 Introduction ● Who: – Bruce Beckles, e-Science Specialist, UCS ● What: – Programming: Input and Output in Python course, Day One – Part of the Scientific Computing series of courses ● Contact (questions, etc): – ● Health & Safety, etc: – Fire exits Please switch off mobile phones!

3 Related/Follow-on courses “Programming: Checkpointing in Python”:Programming: Checkpointing in Python – More robust Python programs that can save their current state and restart from that saved state at a later date – “Programming: Input and Output in Python” is a pre-requisite for the “Programming: Checkpointing in Python” course “Pattern Matching Using Regular Expressions”:Pattern Matching Using Regular Expressions – Understanding and constructing regular expressionsregular expressions “Programming: Gnuplot for Simple Graphs”:Programming: Gnuplot for Simple Graphs – Using gnuplot to create graphical output from datagnuplot

4 Pre-requisites ● Ability to use a text editor under Unix/Linux: – Try gedit if you aren’t familiar with any other Unix/Linux text editors ● Basic familiarity with the Python language (as would be obtained from the “Programming: Python for Absolute Beginners” course):Programming: Python for Absolute Beginners – Interactive and batch use of Python – Basic concepts: variables, flow of control, functions – Simple data manipulation – Simple file I/O (reading and writing to files) – Structuring programs (using functions, modules, etc)

5 Start a shell

6 Screenshot of newly started shell

7 Python Interpreter on PWF Linux

8 Python Interpreter: initial screen

9 Input and Output 1. Files 3. The command line 2. Standard input and output

10 input data file Python script output data file > command output

11 input data file Python script output data file input data file input data file output data file output data file

12 Reading a file 3. Closing the file 1. Opening a file 2. Reading from the file

13 Opening a file 'data.txt' line one\n line two\n line three\n line four\n filesystem node position in file type: file file name type: string the data on disc

14 'data.txt' >>> data = open () file nametype: string Python command Python file object type: file refers to the file with name 'data.txt' initial position at start of data

15 >>>data= open('data.txt') >>> data.readline() the Python file object a dot a “method” 'line one\n' first line of the file complete with “\n” >>> 'line two\n' data.readline() same command again second line of file Reading a file

16 >>> data = open('data.txt') line one\n line two\n line three\n line four\n data position: start of file

17 >>> data = open('data.txt') line one\n line two\n line three\n line four\n >>> data.readline() 'line one\n' data position: after end of first line, at start of second line

18 >>> data = open('data.txt') line one\n line two\n line three\n line four\n >>> data.readline() 'line two\n' >>> data.readline() 'line one\n' data position: after end of read data, at start of unread data

19 >>>datareadlines(). [ 'line three\n', 'line four\n' ] >>>datareadline(). 'line one\n' >>>datareadline(). 'line two\n' remaining unread lines in the file

20 >>> data = open('data.txt') line one\n line two\n line three\n line four\n >>> data.readlines() [ 'line three\n', 'line four\n' ] >>> data.readline() 'line one\n' >>> data.readline() 'line two\n' data position: at end of file

21 data >>> data.readlines() [ 'line three\n', 'line four\n' ] >>> data.close() disconnect Closing a file

22 >>> data.readlines() [ 'line three\n', 'line four\n' ] >>>data.close() >>> del data delete the variable if we aren't going to use it again

23 Common trick Python “magic”: treat the file like a list and it will behave like a list for line in data.readlines(): stuff for line in data: stuff

24 Putting it all together in a function 1.Take a file name as the function argument. 2.Read a file of “key/value” lines. 3.Create the equivalent dictionary. 4.Return the dictionary. Hhydrogen Hehelium Lilithium Beberyllium Bboron elements.txt

25 1. Create an empty dictionary. 2. Open the file. 3. For each line in the file: 3a. Split the line into two strings (key & value). 3b. Add the key and value to the dictionary. 4. Close the file. 5. Return the dictionary. The function

26 utils.py def file2dict(filename): dict = {} data = open(filename) for line in data: [ key, value ] = line.split() dict[key] = value data.close () return dict Simple, really.

27 #!/usr/bin/python import utils elements = utils.file2dict('elements.txt') utils.print_dict(elements) mkdict.py

28 >>> data = open('output') Traceback (most recent call last): File " ", line 1, in ? IOError: [Errno 2] No such file or directory: 'output' What if something goes wrong? data.txt output >>> data = open('data.txt') >>> data.readlines() Traceback (most recent call last): File " ", line 1, in ? IOError: [Errno 13] Permission denied

29 >>> data = open('output') Traceback (most recent call last): File " ",line 1, in ? IOError:No such file or directory “Traceback”: the command's history “stdin”: “standard input” = the terminal Only one line of command Type of exception (error) Error message : 'output' [Errno 2] Error number

31 def file2dict(filename): import sys dict={} try: data = open(filename) for line in data: [ key, value ] = line.split() dict[key] = value data.close() except IOError: print "Problem with file %s" % filename print "Aborting!" data.close() sys.exit(1) return dict utils.py

32 >>> import utils >>> mydict = utils.file2dict('output') Problem with file output Aborting! Traceback (most recent call last): File " ", line 1, in ? File "utils.py", line 82, in file2dict data.close() UnboundLocalError: local variable 'data' referenced before assignment

33 def file2dict(filename): import sys dict={} data = None try: data = open(filename) for line in data: [ key, value ] = line.split() dict[key] = value data.close() except IOError: print "Problem with file %s" % filename print "Aborting!" if type(data) == file: data.close() sys.exit(1) return dict utils.py

34 >>> import utils >>> mydict = utils.file2dict('output') Problem with file output Aborting! >

35 def file2dict(filename): import sys dict={} data = None try: data = open(filename) for line in data: [ key, value ] = line.split() dict[key] = value data.close() except IOError, error: (errno, errdetails) = error print "Problem with file %s: %s" % (filename, errdetails) print "Aborting!" if type(data) == file: data.close() sys.exit(1) return dict utils.py

36 >>> import utils >>> mydict = utils.file2dict('output') Problem with file output: No such file or directory Aborting! >

37 >>> line = "Too many values" >>> [ key, value ] = line.split() Traceback (most recent call last): File " ", line 1, in ? ValueError: too many values to unpack >>> line = "notenough!" >>> [ key, value ] = line.split() Traceback (most recent call last): File " ", line 1, in ? ValueError: need more than 1 value to unpack

38 What about output? input=open('input.txt') 'r' input=open('input.txt'), 'w' output=open('output.txt'), equivalent open for reading open for writing

39 Opening a file for writing 'output.txt' filesystem node position in file empty file start of file

40 >>>output=open( 'output.txt', 'w ' ) file nameopen for writing

41 >>>output=open('output.txt','w ' ) >>>output. write ( 'alpha\n' ) alpha\n method to write a lump of data lump of data to be written lump: not necessarily a whole line

42 >>>output=open('output.txt','w ' ) >>>output.write( 'bet' ) alpha\n bet >>>output.write('alpha\n') lump of data to be written

43 >>>output=open('output.txt','w ' ) >>>output.write( 'a\n' ) alpha\n beta\n >>>output.write('alpha\n') >>>output.write('bet') remainder of the line

44 >>>output=open('output.txt','w ' ) >>>output. writelines ( 'a\n' ) alpha\n beta\n gamma\n delta\n >>>output.write('alpha\n') >>>output.write('bet') >>>output.write( ['gamma\n', 'delta\n'] ) method to write a list of lumps the list of lumps (typically lines)

45 >>>output=open('output.txt','w ' ) >>>output. writelines( 'a\n' ) >>>output.write('alpha\n') >>>output.write('bet') >>>output.write( ['gamma\n', 'delta\n'] ) >>>output. close() Python is done with this file. Only at this point is it guaranteed that the data is on the disc!

46 Accessing the system 1. Files 3. The command line 2. Standard input and output The “sys” module

47 The “sys” module >>> import sys Access to general “system” things Standard input and output The command line Information about the Python environment

48 command.py<input.dat>output.dat Python script as a command Standard input from input.dat Standard output to output.dat

49 Inside the python script import sys sys.stdin sys.stdout “standard output” “standard input” import the module treat exactly like an open(…, 'r') file treat exactly like an open(…, 'w') file

50 So, what does this script do? #!/usr/bin/python import sys for line in sys.stdin: sys.stdout.write(lin e) Read lines in from standard input Write them out again to standard output It copies files, line by line

51 ● Access to files ● Opening ● Reading/writing ● Closing ● sys module ● standard input ● standard output

52 > curve.py0.25 Command line arguments Python script as a command Single command line argument

53 curve.py #!/usr/bin/python import sys sys.argv print import the sys module sys.argv — the command line arguments argument values

54 >curve.py0.25 [ '/home/rjd4/bin/curve.py', '0.25' ] The file name of the script itself The command line argument as a string! sys.argv[0] sys.argv[1]

55 curve.py #!/usr/bin/python import sys sys.argv[1] print sys.argv[1] — the 1 st command line argument

56 >curve.py0.25 '0.25' 1 st command line argument as a string

'0.25' string float printfloat('0.25')

58 curve.py #!/usr/bin/python import sys sys.argv[1]print float() float() converts strings to floats float() converts things to floats

59 >curve.py st command line argument as a float

60 2a.Write a function that parses the command line for a float and an integer. #!/usr/bin/python import sys def parse_args(): pow = float(sys.argv[1]) num = int(sys.argv[2]) return (pow, num) def power_curve(pow, num_points): … curve.py

61 2b.Write a script that tests that function. #!/usr/bin/python …functions… # power_curve(0.5, 5) (r, N) = parse_args() print 'Power: ', r, type(r) print 'Points: ', N, type(N) > curve.py Power: 0.5 Points: 5 ✔ Right values Right types ✔ curve.py

62 3.Combine the two functions. #!/usr/bin/python …functions… …tests (commented out)… (pow, num) = parse_args() power_curve(pow, num) curve.py

63 Any questions?