Python Input and Output | Python 3 Inputs Outputs Tutorial 2019

Python Tutorials

Python Input and Output Tutorial For Beginners 2019. Here in this blog post Coding compiler sharing Python 3 Inputs and Outputs tutorial for beginners. You will learn about Python IO. This Python tutorial is for absolute beginners who are looking for learning Python programming. Let’s start learning Python 3.

Python Input and Output

A program can have several output methods: print data in a human readable manner, or write a file for later use. This chapter will discuss several possibilities.

Related Articles: Python Getting Started Guide  |  Introduction to Python

1. Formatted output

We have two very different output value method: expression statements and the print () function (A third way is to use the file object write()methods, standard output file can reference sys.stdout, See the Library Reference Manual).

Normally, you want more formatting control over the output, rather than simply printing a space-separated value. There are two ways to format your output: The first method is to handle the entire string by yourself, and you can create any output form you want by using string cuts and join operations. The string type contains some useful operations for populating the string with the width of the specified column, which will be discussed later. The second method is to use the str.format()method.

The standard module string includes operations that are useful when filling a given column with a string. We will discuss this part later. The second method is to use the Template method.

Of course, there is a problem, how to convert the value into a string? Fortunately, Python has a way to convert any value to a string: pass it into the repr() or str() function.

The function str() is used to convert values into human-readable form, and repr() is converted to a form that is read by the interpreter (if there is no equivalent syntax, a SyntaxError exception occurs ).

Reading the interpretation of the form, str () will return the same value as repr () . Many types of structures, such as numeric or linked lists and dictionaries, have a unified interpretation of each function. Strings and floating-point numbers have a unique way of reading.

Here are some examples:

>>> s  =  'Hello, world.' 
>>> str ( s ) 
'Hello, world.' 
>>> repr ( s ) 
"'Hello, world.'" 
>>> str ( 1 / 7 ) 
'0.14285714285714285 ' 
>>> x  =  10  *  3.25 
>>> y  =  200  *  200 
>>> s  =  'The value of x is '  +  repr ( x )  +  ', and y is ' +  repr ( y)  +  '...' 
>>> print ( s ) 
The value of x is 32.5, and y is 40000... 
>>> # The repr() of a string adds string quotes and backslashes: 
... hello  =  'hello, world \n ' 
>>> hellos  =  repr ( hello ) 
>>> print ( hellos ) 
'hello, world\n' 
>>> # The argument to repr() may be any Python object: 
... repr (( x ,  y ,  ( 'spam' , 'eggs'))) 
"(32.5, 40000, ('spam', 'eggs'))"

There are two ways to write square and cubic tables:

>>> for  x  in  range ( 1 ,  11 ): 
...     print ( repr ( x ) . rjust ( 2 ),  repr ( x * x ) . rjust ( 3 ),  end = ' ' ) 
...     # Note Use of 'end' on previous line 
...     print ( repr ( x * x * x ) . rjust ( 4)) 
... 
1 1 1 
2 4 8 
3 9 27 
4 16 64 
5 25 125 
6 36 216 
7 49 343 
8 64 512 
9 81 729 
10 100 1000

>>> for  x  in  range ( 1 ,  11 ): 
...     print ( ' {0:2d} {1:3d} {2:4d} ' . . format ( x , x * x , x * x * x ) ) ... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000    

(Note that in the first example, print() adds a space between each column. It always includes spaces between the arguments.)

Related Article: Python Interpreter Tutorial

The above is a demonstration of the str.rjust() method, which outputs a string to a column and aligns it to the right by padding the space to the left. Similar methods are str.ljust() and str.center() .

These functions simply output a new string and do not change anything. If the output string is too long, they will not truncate it, but output as it is, which will confuse your output format, but it will always be stronger than the alternative (truncate the string) because that will cause an error. The output value (if you really need to truncate it, you can use a cut operation, for example: x.ljust(n)[:n]).

There is another method, str.zfill(), which is used to fill the left side of a numeric string representation with 0. The function can correctly understand the sign:

>>> '12' . zfill ( 5 ) 
'00012' 
>>> '-3.14' . zfill ( 7 ) 
'-003.14' 
>>> '3.14159265359' . zfill ( 5 ) 
'3.14159265359'

The basic usage of method str.format() is as follows:

>>> print ( 'We are the {} who say " {} !"' . format ( 'knights' ,  'Ni' )) 
We are the knights who say "Ni!"

Curly braces and their characters are replaced with the arguments passed to str.format() . The value in the braces indicates which of the objects passed into the str.format() method:

>>> print ( ' {0} and {1} ' . format ( 'spam' ,  'eggs' )) 
spam and eggs 
>>> print ( ' {1} and {0} ' . format ( 'spam' ,  'eggs' )) 
eggs and spam

If you use the keyword argument when calling str.format() , you can refer to the value by its parameter name:

>>> print ( 'This {food} is {adjective} .' . format ( 
...       food = 'spam' ,  adjective = 'absolutely horrible' )) 
This spam is absolutely horrible.

Positional parameters and keyword parameters can be freely combined:

>>> print ( 'The story of {0} , {1} , and {other} .' . format ( 'Bill' ,  'Manfred' , 
                                                       other='Georg'))) 
The story of Bill, Manfred, and Georg .

'!a'(Applying ascii() ), '!s'(using str() ) and '!r'(applying repr() ) can convert values before formatting:

>>> import  math 
>>> print ( 'The value of PI is approximately {} .' . format ( math . pi )) 
The value of PI is approximately 3.14159265359. 
>>> print ( 'The value of PI is approximately { !r} .' . format ( math . pi )) 
The value of PI is approximately 3.141592653589793.

After allows the optional field name ':'and format commands. This allows more in-depth control of the formatting of the values. The following example converts Pi to three-digit precision.

>>> Import  Math 
>>> Print ( 'IS Approximately the PI of The value of {0: .3f} .' . The format ( Math . PI )) 
of The value of the PI IS Approximately 3.142.

In the field ':'behind the increase will be an integer defining the minimum width of the field, which is useful when beautification table:

>>> table  =  { 'Sjoerd' :  4127 ,  'Jack' :  4098 ,  'Dcab' :  7678 } 
>>> for  name ,  phone  in  table . items (): 
...     print ( ' {0:10} = => {1:10d} ' . format ( name ,  phone )) 
... 
Jack ==> 4098 
Dcab ==> 7678 
Sjoerd ==> 4127

If you have a really long format string, don’t want to split it. If you can refer to the formatted variable instead of the position by name. There is a simple way to pass in a dictionary and '[]'access its keys with brackets ( ):

>>> table  =  { 'Sjoerd' :  4127 ,  'Jack' :  4098 ,  'Dcab' :  8637678 } 
>>> print ( 'Jack: {0[Jack]:d} ; Sjoerd: {0[Sjoerd]:d } ; ' 
          'Dcab: {0[Dcab]:d}'.format(table)) 
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

You can also use the ‘**’ flag to pass this dictionary as a keyword argument:

>>> table  =  { 'Sjoerd' :  4127 ,  'Jack' :  4098 ,  'Dcab' :  8637678 } 
>>> print ( 'Jack: {Jack:d} ; Sjoerd: {Sjoerd:d} ; Dcab: {Dcab :d} ' . format ( ** table )) 
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This is very effective in combination with the new built-in function vars() . This function returns a dictionary containing all local variables.

Related Articles: Learn Python In One Day

To learn more about string formatting method str.format () , see the format string syntax .

1.1. Old-style string formatting

Operator %also be a string format. It sprintf()parses the left argument in a similar -style manner, applies the right argument to this, and gets the string generated by the formatting operation, for example:

>>> import  math 
>>> print ( 'The value of PI is about %5.3f .'  %  math . pi ) 
The value of PI is approximately 3.142.

More information can be found in the printf-style String Formatting section.

2. Reading and Writing Files

Function open () returns a file object , commonly used with two arguments: .open(filename, mode)

>>> f  =  open ( 'workfile' ,  'w' )

The first parameter is a string containing the file name. The second parameter is also a string containing several characters that describe how to use the file. mode is 'r'when showing only read files; 'w'represents only written to the file (the file with the same name already exists will be deleted); 'a'denotes open file is additionally written to any data files will be automatically added to the end. 'r+'Indicates that the file is opened for reading and writing. The mode parameter is optional and defaults to 'r'.

Typically, the file to text open, which means that you read from the file and the string will be written to the file specified encoding (default is UTF-8) encoding. Mode back 'b'to binary mode to open a file: data is read and written in bytes of the object. This mode should be used for all files that do not contain text.

Related Article: Python For Machine Learning

In text mode, when reading, the platform-dependent line terminator (on Unix, yes \non Windows \r\n) is converted to \n. When writing in text mode, the default will appear \nconverted into a platform-dependent line terminator. This is not secretly modified for ASCII text files, but will damage JPEGor EXEdata such as a binary file. Use binary mode to read and write such files with special care.

2.1. File Object Methods

The examples in this section will assume that a file object fhas been created.

To read the contents of a file, it needs to be called f.read(size). This method reads a number of data and returns its contents as a string. size is an optional value, specifying the length of the string. If you do not specify size or specify a negative number, the entire file will be read and returned.

Problems arise when the file size is twice the current machine memory. On the other hand, will try to press the relatively large size are read and returned. If it reaches the end of the file, f.read()an empty string ( '') is returned :

>>> f . read () 
'This is the entire file.\n' 
>>> f . read () 
''

f.readline()Reading a single line from the file will automatically add a newline ( \n) at the end of the string . This operation will be ignored only if the last line of the file does not end with a newline character.

Related Article: Python Data Structures

This makes the return value there would be confusion if f.readline()returns an empty string, it means reached the end of the file, while a blank line is represented as '\n'a string containing only a newline:

>>> f . readline () 
'This is the first line of the file.\n' 
>>> f . readline () 
'Second line of the file\n' 
>>> f . readline () 
''

You can loop through the file object to read each line in the file. This is a memory efficient, fast, and code-introduced way:

>>> for  line  in  f : 
...     print ( line ,  end = '' ) 
... 
This is the first line of the file. 
Second line of the file

If you want to read all the lines in a file list, you can also use list(f)or f.readlines().

f.write(string)The method writes the contents of the string to the file and returns the length of the written character:

>>> f . write ( 'This is a test \n ' ) 
15

To write other non-string content, first convert it to a string:

>>> value  =  ( 'the answer' ,  42 ) 
>>> s  =  str ( value ) 
>>> f . write ( s ) 
18

f.tell()Returns an integer representing the file’s pointer to the file object. This value measures the number of bits from the beginning of the file to the pointer. Need to change the file object pointer, use f.seek(offset,from_what). The pointer moves the offset bit from the specified reference position in this operation . The reference position is specified by the from_what parameter.

A from_what value of 0 indicates that the file starts at the beginning, 1 indicates the current file pointer position, and 2 indicates the end of the file. From_what can be ignored, the default value is zero, from the beginning of the file:

>>> f  =  open ( 'workfile' ,  'rb+' ) 
>>> f . write ( b '0123456789abcdef' ) 
16 
>>> f . seek ( 5 )      # Go to the 6th byte in the file 
5 
>>> f . read ( 1 ) 
b'5' 
>>> f . seek ( - 3 ,  2 )  # Go to the 3rd byte before the end 
13 
>>> f .Read( 1 ) 
b'd'

In a text file (not in bthe open mode), only the start looking for the file header (The exception is looking for the end of the file) and valid offset value can only be returned value or zero. Any other offset values produce undefined behavior.seek(0, 2)f.tell()

When you have finished using a file, call the f.close()method you can close it and release all the system resources they occupy. In calling f.close()the method, try to use the file object will automatically fail again.

>>> f . close () 
>>> f . read () 
Traceback (most recent call last): 
  File "<stdin>" , line 1 , in ? 
ValueError : I/O operation on closed file

It is a good practice to use the keyword with file objects. Its advanced feature is that it automatically shuts down when the file is used up. Even if an exception occurs, it does not matter. It is a shorthand for try – finally blocks:

>>> with  open ( 'workfile' ,  'r' )  as  f : 
...     read_data  =  f . read () 
>>> f . closed 
True

File objects have some less frequently used additional methods, such isatty()and truncate()there is a complete guide to file objects in the Library Reference.

Related Article: Python Modules

2.2. Using json to store structured data

Reading and writing strings from a file is easy. Value more than is necessary to charge something trouble, because read()the method will return a string, it should be passed int () This function may be '123'such a string into a numeric value 123. When you want to save more complex data types, such as nested lists and dictionaries, parsing and serializing them manually will become more complicated.

Fortunately, users do not have to write and debug code that saves complex data types. Python allows you to use the common data exchange format JSON (JavaScript Object Notation) . Standard module json acceptable Python data structures, and converts them to a string representation; this process is called serialization .

Reconstruct the data structure from the string representation is called a deserialization . In the process of serialization and deserialization, the character string representing the object may be stored in a file or data, or may be transmitted to a remote machine through a network connection.

Note: The JSON format is often used for data exchange in modern applications. Many programmers are already familiar with it, making it a good choice for collaboration.

If you have an object x, you can view its JSON string representation with a simple line of code:

>>> json . dumps ([ 1 ,  'simple' ,  'list' ]) 
'[1, "simple", "list"]'

Another variant of the dumps () function, dump() , serializes objects directly to a file. So if fis open for writing a file object , we can do this:

Json . dump ( x ,  f )

In order to re-decoded, if fis opened for reading the file object :

x  =  json . load ( f )

This simple serialization technique can handle lists and dictionaries, but serializing arbitrary class instances into JSON requires a little extra effort. The json module manual explains this in detail.

Related Articles: 

Python Interview Questions

Python Programming Interview Questions

Leave a Reply

Your email address will not be published. Required fields are marked *