Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 9 Structures and Sequential Access Files.
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
The printf Method The printf method is another way to format output. It is based on the printf function of the C language. System.out.printf(,,,..., );
Working with Files CSC 161: The Art of Programming Prof. Henry Kautz 11/9/2009.
05/09/2015SJF L31 F21SF Software Engineering Foundations Formatting Converting numbers to Strings and vice versa Monica Farrow EM G30
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
Introduction to Python
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Lecture 16 – Open, read, write and close files.  At the end of this lecture, students should be able to:  understand file structure  open and close.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
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.
Introducing Python CS 4320, SPRING Format: Field widths and Alignment The string representation of a value can be padded out to a specific width.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Strings CS303E: Elements of Computers and Programming.
Built-in Data Structures in Python An Introduction.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Chapter 8 : Binary Data Files1 Binary Data Files CHAPTER 8.
Python: Input and Output Yuen Kwan Lo. Output Format str( ) and repr( ) same representation but String and Floating point number a=0.24 str(a)‘0.24’ repr.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
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.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
 Python’s ‘math’.  Modules.  Files.  Python’s ‘time’.  Classes in python.
Files Tutor: You will need ….
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
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])
ASC, National Centre for Physics Programming Python – Lecture#2 Mr. Adeel-ur-Rehman.
Trinity College Dublin, The University of Dublin GE3M25: Computer Programming for Biologists Python, Class 2 Karsten Hokamp, PhD Genetics TCD, 17/11/2015.
ME-2221 COMPUTER PROGRAMMING Lecture 18 FILE OPERATIONS Department of Mechanical Engineering A.H.M Fazle Elahi Khulna University of engineering & Technology.
Input and Output in python Josh DiCristo. How to output numbers str()  You can put any variable holding a number inside the parentheses and it will display.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
Lecture 4 Python Basics Part 3.
5 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 9 Structures and Sequential Access Files.
Files A collection of related data treated as a unit. Two types Text
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
Lakshit Dhanda. Output Formatting Python has ways to convert any value to a string. 2 Methods repr() – meant to generate representations of values read.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Programming Training Main Points: - More Fundamental algorithms on Arrays. - Reading / Writing from files - Problem Solving.
Kanel Nang.  Two methods of formatting output ◦ Standard string slicing and concatenation operations ◦ str.format() method ie. >>> a = “The sum of 1.
Python focus – files The open keyword returns a file object Opening a file myFile = open('C:\file.txt', arg) Optional argument The second argument controls.
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.
Introduction to Programming
Fundamentals of Programming I Overview of Programming
Microsoft Visual Basic 2005: Reloaded Second Edition
COMPSCI 107 Computer Science Fundamentals
Lecture 4 Python Basics Part 3.
TMF1414 Introduction to Programming
Python’s input and output
Session #5 File I/O Bit Masks, Fields & Bit Manipulations
CS111 Computer Programming
Binary Files.
Lecture 13 Input/Output Files.
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Lecture 4 Python Basics Part 3.
Text and Binary File Processing
File Input and Output.
Input and Output with FILES
Fundamentals of Python: First Programs
Introduction to Value-Returning Functions: Generating Random Numbers
15-110: Principles of Computing
Topics Introduction to File Input and Output
Terminal-Based Programs
COMPUTER PROGRAMMING SKILLS
Topics Introduction to File Input and Output
Presentation transcript:

Python’s input and output Chenghao Wang

Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello World”) - Hello World S=“Hello World” Str(s) - ‘Hello World’ S=“Hello World” Repr(s) - “‘Hello World’” Difference between str( ) and repr() The str() function is meant to return representations of values which are fairly human-readable. The repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax).

Fancier Output Formatting – Formatting Method ▪str.rjust() ▪str.ljust() ▪str.center() The str.rjust() method can right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods str.ljust() and str.center().

Fancier Output Formatting – Formatting Method ▪str.zfill() ▪str.format() Example '12'.zfill(5) -> '00012' '-3.14'.zfill(7) -> ' ' ' '.zfill(5) ->' ' This method returns the numeric string left filled with zeros in a string of length width. This method can replace the brackets and characters with the objects passed into. Example print('We are the {} who say "{}!"'.format('knights', 'Ni')) -> We are the knights who say "Ni!" Example 2 print('This {food} is {adjective}.'.format(... food='spam', adjective='absolutely horrible')) ->This spam is absolutely horrible. Example 3 import math print('The value of PI is approximately {0:.3f}.'.format(math.pi)) ->The value of PI is approximately An optional ':' and format specifier can follow the field name.

Fancier Output Formatting – Old Formatting Method ▪The % operator Example import math print('The value of PI is approximately %5.3f.' % math.pi) ->The value of PI is approximately The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation.

Reading Files ▪open(filename, mode) Example f = open('workfile', 'w') f = open('filename', ‘r') Mode ’r’ -> open the file only for reading Mode ’w’ -> only writing (erase file with the same time) Mode ’a’ -> opens the file for appending Mode ’r+’ -> open the file for reading and writing Mode ‘b’ -> opens the file in binary mode

Reading Files ▪f.read(size) Example f.read() ->'This is the entire file.\n‘ f.read() ->' This method reads some quantity of data and returns it as a string or bytes object. When size is negative or omitted, then return the entire content; When the end of the file has been reached, then return empty string ‘’

Reading Files ▪f.readline() Example f.readline() ->'This is the first line of the file.\n' f.readline() ->'Second line of the file\n' f.readline() ->'' This method reads a single line from the file;

Writing Files ▪f.write(string) ▪f.tell() Example f.write('This is a test\n') ->15 This method writes the contents of string to the file, returning the number of characters written. To write something other than a string, it needs to be converted to a string first. Example value = ('the answer', 42) s = str(value) f.write(s) ->18 This method returns an integer giving the file object’s current position

Writing Files ▪f.seek(offset, from_what) ▪f.close() Example f = open('workfile', 'rb+') f.write(b' abcd ef') ->16 f.seek(-3, 2) # Go to the 3rd byte before the end ->13 f.read(1) ->b'd' The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point, omitted means from the beginning of the file. After the writing is done, use this to close.

Saving structured data with json - Overview ▪json json.dumps([1, 'simple', 'list']) ->'[1, "simple", "list"]' Python allows users to use the popular data interchange format called JSON (JavaScript Object Notation) to take Python data hierarchies, and convert them to string representations If you have an object x, you can view its JSON string representation with a simple line of code: Another variant of the dumps() function, called dump(), simply serializes the object to a text file. So if f is a text file object opened for writing, we can do this: json.dump(x, f) To decode the object again, if f is a text file object which has been opened for reading: x = json.load(f))

Thanks 5/21/2014 Works Citation The Python Tutorial put.html# Json’s Overview and python-related operations for json 11/12/14/ html