Python Tutorial (26) - Input and Output

Time: Column:Python views:211

Input and Output in Python

In the previous chapters, we’ve already encountered Python's input and output functionalities. In this chapter, we will take a deeper dive into Python's input and output operations.

Formatting Output

Python provides two ways to output values: expression statements and the print() function.

A third method is to use the write() method of file objects, with the standard output file referred to by sys.stdout.

If you want more flexible output formatting, you can use the str.format() function to format the output values.

To convert the output values into strings, you can use the repr() or str() functions:

  • str(): Returns a string representation that is readable for end users.

  • repr(): Returns a string representation that is readable for the interpreter.

For example:

>>> s = 'Hello, Runoob'
>>> str(s)
'Hello, Runoob'
>>> repr(s)
"'Hello, Runoob'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is: ' + repr(x) + ', and the value of y is: ' + repr(y) + '...'
>>> print(s)
The value of x is: 32.5, and the value of y is: 40000...

The repr() function can also escape special characters in a string:

>>> hello = 'hello, runoob\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, runoob\n'

You can use repr() with any Python object:

>>> repr((x, y, ('Google', 'Runoob')))
"(32.5, 40000, ('Google', 'Runoob'))"

Outputting Tables

Here are two ways to output a table of squares and cubes:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     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

Another way:

>>> 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: In the first example, the spaces between columns are added by print().

The above example demonstrates the rjust() method, which right-justifies strings and pads them with spaces on the left. Similar methods include ljust() and center(). These methods don’t write anything to the screen but return new strings.

Another method, zfill(), pads a numeric string on the left with zeros:

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

Using str.format()

The basic usage of str.format():

>>> print('{} website: "{}!"'.format('PMeve', 'www.pmeve.com'))
PMeve website: "www.pmeve.com!"

The curly braces and the characters inside them (known as format fields) are replaced by the arguments passed to format().

You can reference positional arguments by their index:

>>> print('{0} and {1}'.format('Google', 'PMeve'))
Google and Runoob
>>> print('{1} and {0}'.format('Google', 'PMeve'))
Runoob and Google

You can also reference keyword arguments:

>>> print('{name} website: {site}'.format(name='PMeve', site='www.pmeve.com'))
PMeve website: www.pmeve.com

Positional and keyword arguments can be combined:

>>> print('Website list: {0}, {1}, and {other}.'.format('Google', 'PMeve', other='Taobao'))
Website list: Google, PMeve, and Taobao.

You can use !a (for ascii()), !s (for str()), and !r (for repr()) to convert values before formatting them:

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

The format specifier can follow a colon : to specify width, precision, or alignment. For example, to format Pi to three decimal places:

>>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))
The value of PI is approximately 3.142.

You can ensure a field has a minimum width, which is useful for formatting tables:

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> for name, number in table.items():
...     print('{0:10} ==> {1:10d}'.format(name, number))
...
Google     ==>          1
Runoob     ==>          2
Taobao     ==>          3

If you have a long format string, you can use variable names instead of positions for easier readability. One way is to pass a dictionary and use square brackets to access the keys:

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> print('Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table))
Runoob: 2; Google: 1; Taobao: 3

You can achieve the same with the ** operator:

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> print('Runoob: {Runoob:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table))
Runoob: 2; Google: 1; Taobao: 3

Old-Style String Formatting

The % operator can also be used for string formatting. It takes the left argument as a format string, similar to sprintf(), and the right argument as the values to substitute, returning the formatted string. For example:

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

Since str.format() is a newer function, most Python code still uses the % operator. However, as this old-style formatting will eventually be removed from the language, it's recommended to use str.format().


Reading Keyboard Input

Python provides the built-in input() function to read a line of text from standard input, typically the keyboard.

Example:

#!/usr/bin/python3

str = input("Please enter something: ")
print("You entered: ", str)

This will produce an output corresponding to the user input:

Please enter something: Runoob Tutorial
You entered:  Runoob Tutorial

Reading and Writing Files

The open() function returns a file object. The basic syntax is as follows:

open(filename, mode)
  • filename: A string that contains the name of the file you want to access.

  • mode: Specifies the mode in which the file is opened, such as read-only, write, append, etc. This parameter is optional, and the default mode is read (r).

File Opening Modes

ModeDescription
rOpens a file for reading only. The file pointer is placed at the beginning of the file. (Default)
rbOpens a file for reading in binary format. The file pointer is placed at the beginning.
r+Opens a file for both reading and writing. The file pointer is placed at the beginning.
rb+Opens a file for both reading and writing in binary format. The file pointer is placed at the beginning.
wOpens a file for writing only. If the file exists, it overwrites the file. If it doesn’t exist, a new file is created.
wbOpens a file for writing in binary format. If the file exists, it overwrites the file. If it doesn’t exist, a new file is created.
w+Opens a file for reading and writing. If the file exists, it overwrites the file. If it doesn’t exist, a new file is created.
wb+Opens a file for reading and writing in binary format. If the file exists, it overwrites the file. If it doesn’t exist, a new file is created.
aOpens a file for appending. The file pointer is placed at the end of the file. If the file doesn’t exist, it creates a new one.
abOpens a file for appending in binary format. The file pointer is placed at the end of the file. If the file doesn’t exist, it creates a new one.
a+Opens a file for both reading and appending. The file pointer is placed at the end of the file. If the file doesn’t exist, it creates a new one.
ab+Opens a file for both reading and appending in binary format. The file pointer is placed at the end of the file. If the file doesn’t exist, it creates a new one.

The following table summarizes these modes:

Python Tutorial (26) - Input and Output

ModeReadWriteCreateOverwritePointer at StartPointer at End
rYesNoNoNoYesNo
r+YesYesNoNoYesNo
wNoYesYesYesYesNo
w+YesYesYesYesYesNo
aNoYesYesNoNoYes
a+YesYesYesNoNoYes

Writing to a File

Here is an example of writing a string to a file called foo.txt:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "w")

f.write("Python is a great programming language.\nYes, it truly is!!\n")

# Close the file
f.close()
  • The first argument is the filename to open.

  • The second argument specifies the mode in which the file should be opened. If you use 'r', the file is opened for reading only. If you use 'w', the file is opened for writing. If the file already exists, it is overwritten; if it doesn’t exist, a new file is created. Similarly, 'a' opens the file in append mode.

Opening the file foo.txt will show the following content:

$ cat /tmp/foo.txt 
Python is a great programming language.
Yes, it truly is!!

File Object Methods

In the remaining examples in this section, assume that a file object named f has been created.


f.read()

To read the contents of a file, use f.read(size). This will read a specific amount of data and return it as a string or bytes object.

  • size is an optional numeric argument. If it is omitted or negative, the entire content of the file will be read and returned.

The following example assumes that the file foo.txt already exists (created in the previous example):

Example:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

str = f.read()
print(str)

# Close the file
f.close()

Output:

Python is a great programming language.
Yes, it truly is!!

f.readline()

f.readline() reads a single line from the file. A newline character (\n) is returned at the end of the line. If it returns an empty string, the end of the file has been reached.

Example:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

str = f.readline()
print(str)

# Close the file
f.close()

Output:

Python is a great programming language.

f.readlines()

f.readlines() returns all lines in the file as a list of strings.

  • If an optional argument sizehint is provided, it reads up to that number of bytes and splits them into lines.

Example:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

str = f.readlines()
print(str)

# Close the file
f.close()

Output:

['Python is a great programming language.\n', 'Yes, it truly is!!\n']

Alternatively, you can iterate over the file object to read each line:

Example:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "r")

for line in f:
    print(line, end='')

# Close the file
f.close()

Output:

Python is a great programming language.
Yes, it truly is!!

This method is simple, but it doesn't provide much control. It's best not to mix methods due to different handling mechanisms.


f.write()

f.write(string) writes the specified string to the file and returns the number of characters written.

Example:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo.txt", "w")

num = f.write("Python is a great programming language.\nYes, it truly is!!\n")
print(num)

# Close the file
f.close()

Output:

29

If you want to write something other than a string, you must first convert it:

Example:

#!/usr/bin/python3

# Open a file
f = open("/tmp/foo1.txt", "w")

value = ('www.runoob.com', 14)
s = str(value)
f.write(s)

# Close the file
f.close()

After running this program, opening the file foo1.txt gives:

$ cat /tmp/foo1.txt
('www.runoob.com', 14)

f.tell()

f.tell() returns the current position of the file pointer, which represents the byte offset from the beginning of the file. It returns an integer indicating the current position.


f.seek()

To change the current file pointer's position, use f.seek(offset, from_what).

  • offset: the number of bytes to move from the position defined by from_what.

  • from_what: specifies the reference point:

    • 0: Beginning of the file (default).

    • 1: Current file pointer position.

    • 2: End of the file.

Examples:

  • seek(x, 0): Move the file pointer to x bytes from the start.

  • seek(x, 1): Move the file pointer x bytes from the current position.

  • seek(-x, 2): Move the file pointer x bytes backward from the end.

Example:

>>> f = open('/tmp/foo.txt', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)     # Move to the sixth byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # Move to the third-to-last byte
13
>>> f.read(1)
b'd'
>>> f.close()

In text files (files opened without the b mode), you can only seek relative to the start of the file.

When done with a file, call f.close() to close it and free up system resources. If you attempt to read the file after closing it, an exception will be raised:

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

Using with to Manage Files

It's a good practice to use the with keyword when handling files. It ensures proper closing of the file, even if an error occurs. It's also shorter and more elegant than using try-finally blocks.

>>> with open('/tmp/foo.txt', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

The pickle Module

Python’s pickle module allows you to serialize and deserialize objects (i.e., save and load objects to and from files).

Basic Interface:

  • pickle.dump(obj, file [,protocol]): Serializes obj and saves it to file.

  • pickle.load(file): Reads from file and reconstructs the original Python object.

Example 1:

#!/usr/bin/python3
import pickle

# Save data objects to a file using pickle
data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()

Example 2:

#!/usr/bin/python3
import pprint, pickle

# Load Python objects from a pickle file
pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)
pprint.pprint(data1)

data2 = pickle.load(pkl_file)
pprint.pprint(data2)

pkl_file.close()