Python I/O Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Classic file reading 1 infile = open(’filename.txt’, ’r’) for line.

Slides:



Advertisements
Similar presentations
15. Python - Modules A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand.
Advertisements

Perkovic, Chapter 7 Functions revisited Python Namespaces
Computer Science 111 Fundamentals of Programming I Files.
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.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
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.
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.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
H3D API Training  Part 3.1: Python – Quick overview.
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
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.
CSC 107 – Programming For Science. Announcements  Lectures may not cover all material from book  Material that is most difficult or challenging is focus.
5 1 Data Files CGI/Perl Programming By Diane Zak.
Department of Electrical and Computer Engineering Introduction to C++: Primitive Data Types, Libraries and Operations By Hector M Lugo-Cordero August 27,
Geoff Holmes Date Math Weighted Distr Strings String methods Tokenizers System Examples Utility Classes (Chapter 17) import java.util.*;
Introduction As programmers, we don’t want to have to implement functions for every possible task we encounter. The Standard C library contains functions.
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.
Artificial Intelligence Lecture No. 26 Dr. Asad Ali Safi ​ Assistant Professor, Department of Computer Science, COMSATS Institute of Information Technology.
Files Tutor: You will need ….
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.
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)
PHY 107 – Programming For Science. Announcements  Lectures may not cover all material from readings  Material that is most difficult or challenging.
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])
Computer Programming 2 Lab (1) I.Fatimah Alzahrani.
Python Exceptions and bug handling Peter Wad Sackett.
Python Basics Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Reasons to learn Python 1.Short development time 2.Learning curve.
Today… Strings: –String Methods Demo. Raising Exceptions. os Module Winter 2016CISC101 - Prof. McLeod1.
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.
Python Pattern Matching and Regular Expressions Peter Wad Sackett.
Python Lists and Sequences Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark List properties What are lists? A list is a mutable.
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.
Files in Python Opening and Closing. Big Picture To use a file in a programming language – You have to open the file – Then you process the data in the.
Module 5 Working with Data
File I/O File input/output Iterate through a file using for
File Writing Upsorn Praphamontripong CS 1110
CSc 120 Introduction to Computer Programing II
Class 9 Reading and writing to files chr, ord and Unicode
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
File Handling Programming Guides.
Topics Introduction to File Input and Output
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
File I/O File input/output Iterate through a file using for
CS 1111 Introduction to Programming Fall 2018
Introduction to Python: Day Three
Python – a HowTo Peter Wad Sackett and Henrike Zschach.
Python Lists and Sequences
CS190/295 Programming in Python for Life Sciences: Lecture 3
Fundamentals of Functional Programming
CHAPTER 3: String And Numeric Data In Python
Topics Introduction to File Input and Output
Python I/O Peter Wad Sackett.
Introduction to Computer Science
Terminal-Based Programs
Topics Introduction to File Input and Output
Python Simple file reading
CS 1111 Introduction to Programming Spring 2019
Introduction to Computer Science
Presentation transcript:

Python I/O Peter Wad Sackett

2DTU Systems Biology, Technical University of Denmark Classic file reading 1 infile = open(’filename.txt’, ’r’) for line in infile: print(line) # doing something with the line infile.close() Files are opened and closed 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.

3DTU Systems Biology, Technical University of Denmark Classic file reading 2 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() Alternative file reading 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.

4DTU Systems Biology, Technical University of Denmark Classic file writing outfile = open(’filename.txt’, ’w’) outfile.write(”First line in the file\n”) print(”Second line in the file”, file=outfile) outfile.close() File writing 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.

5DTU Systems Biology, Technical University of Denmark 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()

6DTU Systems Biology, Technical University of Denmark 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:

7DTU Systems Biology, Technical University of Denmark 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:

8DTU Systems Biology, Technical University of Denmark 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:

9DTU Systems Biology, Technical University of Denmark 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 = ’ ’ 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: Strings/sequences are zero-based, i.e. first position is 0. Strings have several useful string-only operations.

10DTU Systems Biology, Technical University of Denmark 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 = ’ ’ for i in range(len(mystring)): print(mystring[i]) for character in mystring: print(character)