There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities. Show
7.1. Fancier Output Formatting¶So far we’ve encountered two ways of writing values: expression statements and the Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are several ways to format output.
When you don’t need fancy output but just want a quick display of some variables for debugging purposes, you can convert any value to a string with the
The 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'))" The
7.1.1. Formatted String Literals¶Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string
by prefixing the string with An optional format specifier can follow the expression. This allows greater control over how the value is formatted. The following example rounds pi to three places after the decimal: >>> import math >>> print(f'The value of pi is approximately {math.pi:.3f}.') The value of pi is approximately 3.142. Passing an integer after the >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} >>> for name, phone in table.items(): ... print(f'{name:10} ==> {phone:10d}') ... Sjoerd ==> 4127 Jack ==> 4098 Dcab ==> 7678 Other modifiers can be used
to convert the value before it is formatted. >>> animals = 'eels' >>> print(f'My hovercraft is full of {animals}.') My hovercraft is full of eels. >>> print(f'My hovercraft is full of {animals!r}.') My hovercraft is full of 'eels'. The >>> bugs = 'roaches' >>> count = 13 >>> area = 'living room' >>> print(f'Debugging {bugs=} {count=} {area=}') Debugging bugs='roaches' count=13 area='living room' See self-documenting expressions for more information on the 7.1.2. The String format() Method¶Basic usage of the >>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) We are the knights who say "Ni!" The brackets and characters within them (called format fields) are replaced with the objects passed into the >>> print('{0} and {1}'.format('spam', 'eggs')) spam and eggs >>> print('{1} and {0}'.format('spam', 'eggs')) eggs and spam If keyword
arguments are used in the >>> print('This {food} is {adjective}.'.format( ... food='spam', adjective='absolutely horrible')) This spam is absolutely horrible. Positional and keyword arguments can be arbitrarily combined: >>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', ... other='Georg')) The story of Bill, Manfred, and Georg. If you have a really long format string that you don’t want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position.
This can be done by simply passing the dict and using square 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 This could also be done by passing the >>> 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 particularly useful in combination with the built-in function As an example, the following lines produce a tidily aligned set of columns giving integers and their squares and cubes: >>> 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 For a complete overview of string formatting with 7.1.3. Manual String Formatting¶Here’s the same table of squares and cubes, formatted manually: >>> 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 (Note that the one space between each column was added by the way The There is another method, >>> '12'.zfill(5) '00012' >>> '-3.14'.zfill(7) '-003.14' >>> '3.14159265359'.zfill(5) '3.14159265359' 7.1.4. Old string formatting¶The % operator (modulo) can also be used for string formatting. Given >>> import math >>> print('The value of pi is approximately %5.3f.' % math.pi) The value of pi is approximately 3.142. More information can be found in the printf-style String Formatting section. 7.2. Reading and Writing Files¶
>>> f = open('workfile', 'w', encoding="utf-8") The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file
will be used. mode can be Normally, files are opened in text mode, that means, you read and write strings from
and to the file, which are encoded in a specific encoding. If encoding is not specified, the default is platform dependent (see In text mode, the default when reading is to convert platform-specific line endings ( It is good practice to use the >>> with open('workfile', encoding="utf-8") as f: ... read_data = f.read() >>> # We can check that the file has been automatically closed. >>> f.closed True If you’re not using the Warning Calling After a file object is closed, either by a >>> f.close() >>> f.read() Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: I/O operation on closed file. 7.2.1. Methods of File Objects¶The rest of the examples in this section will assume that a file object called To read a file’s contents, call >>> f.read() 'This is the entire file.\n' >>> f.read() ''
>>> f.readline() 'This is the first line of the file.\n' >>> f.readline() 'Second line of the file\n' >>> f.readline() '' For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code: >>> 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 of a file in a list you can also use
>>> f.write('This is a test\n') 15 Other types of objects need to be converted – either to a string (in text mode) or a bytes object (in binary mode) – before writing them: >>> value = ('the answer', 42) >>> s = str(value) # convert the tuple to string >>> f.write(s) 18
To change the file object’s position, use >>> 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 text files (those opened without a File objects have some additional methods, such as 7.2.2. Saving structured data with json¶Strings can easily be written to and read from a file. Numbers take a bit more effort, since the Rather than having users constantly writing and debugging code to save complicated data types to files, Python allows you to use the popular data interchange format
called JSON (JavaScript Object Notation). The standard module called Note The JSON format is commonly used by modern applications to allow for data exchange. Many programmers are already familiar with it, which makes it a good choice for interoperability. If you have an object >>> import json >>> x = [1, 'simple', 'list'] >>> json.dumps(x) '[1, "simple", "list"]' Another
variant of the To decode the object again, if Note JSON files
must be encoded in UTF-8. Use This simple serialization technique can handle lists and dictionaries, but serializing arbitrary class instances in JSON requires a bit of extra effort. The reference for the
See also
Contrary to JSON, pickle is a protocol which allows the serialization of arbitrarily complex Python objects. As such, it is specific to Python and cannot be used to communicate with applications written in other languages. It is also insecure by default: deserializing pickle data coming from an untrusted source can execute arbitrary code, if the data was crafted by a skilled attacker. When a file is opened in this mode data will be written at the end of the files existing contents?If an existing file is opened in append mode, what happens to the file's existing contents? It will not be erased and new data will be written at the end of the file's current contents.
What will happen when a program opens a file in write mode if the file doesn't exist?If you open a file for writing and the file doesn't exist, then the file is created with 0 length.
What is the proper function used to open a file?C File management. How can we read from and write to file?Method 2: Using File methods
Creating/opening an output file in writing mode. Opening the input file in reading mode. Reading each line from the input file and writing it in the output file. Closing the output file.
|