Python3 Inputoutput
# Python3 Input and Output \\\\n\\\\n## Python3.x Python3 Input and Output\\\\n\\\\nIn the previous chapters, we have already encountered Python's input and output functions. This chapter will provide a detailed introduction to Python's input and output.\\\\n\\\\n## Output Formatting\\\\n\\\\nPython has two ways to output values: expression statements and the `print()` function.\\\\n\\\\nA third way is using the `write()` method of file objects, where the standard output file can be referenced as `sys.stdout`.\\\\n\\\\nIf you want more diverse output formats, you can use the `str.format()` function to format the output values.\\\\n\\\\nIf you want to convert the output values to strings, you can use the `repr()` or `str()` functions.\\\\n\\\\n* **`str()`:** Returns a user-friendly representation of the value.\\\\n* **`repr()`:** Returns a developer-friendly representation of the value.\\\\n\\\\n### Example\\\\n\\\\n>>> s = 'Hello, '\\\\n\\\\n>>> str(s)\\\\n\\\\n'Hello, '\\\\n\\\\n>>> repr(s)\\\\n\\\\n"'Hello, '"\\\\n\\\\n>>> str(1/7)\\\\n\\\\n'0.14285714285714285'\\\\n\\\\n>>> x = 10 * 3.25\\\\n\\\\n>>> y = 200 * 200\\\\n\\\\n>>> s = 'x The value is: ' + repr(x) + ', y The value is:' + repr(y) + '...'\\\\n\\\\n>>> print(s)\\\\n\\\\nx The value is: 32.5, y The value is: 40000...\\\\n\\\\n>>> # repr() The function can escape special characters in strings\\\\n\\\\n... hello = 'hello, tutorialn'\\\\n\\\\n>>> hellos = repr(hello)\\\\n\\\\n>>> print(hellos)\\\\n\\\\n'hello, tutorialn'\\\\n\\\\n>>> # repr() The parameter can be any Python object\\\\n\\\\n... repr((x, y, ('Google', '')))\\\\n\\\\n"(32.5, 40000, ('Google', ''))"\\\\n\\\\nHere are two ways to output a table of squares and cubes:\\\\n\\\\n>>> for x in range(1, 11):\\\\n\\\\n... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')\\\\n\\\\n... # Note the previous line 'end' Usage of\\\\n\\\\n... print(repr(x*x*x).rjust(4))\\\\n\\\\n...\\\\n\\\\n1 1 1\\\\n\\\\n2 4 8\\\\n\\\\n3 9 27\\\\n\\\\n4 16 64\\\\n\\\\n5 25 125\\\\n\\\\n6 36 216\\\\n\\\\n7 49 343\\\\n\\\\n8 64 512\\\\n\\\\n9 81 729\\\\n\\\\n10 100 1000\\\\n\\\\n>>> for x in range(1, 11):\\\\n\\\\n... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))\\\\n\\\\n...\\\\n\\\\n1 1 1\\\\n\\\\n2 4 8\\\\n\\\\n3 9 27\\\\n\\\\n4 16 64\\\\n\\\\n5 25 125\\\\n\\\\n6 36 216\\\\n\\\\n7 49 343\\\\n\\\\n8 64 512\\\\n\\\\n9 81 729\\\\n\\\\n10 100 1000\\\\n\\\\n**Note:** In the first example, the spaces between columns are added by `print()`.\\\\n\\\\nThis example demonstrates the `rjust()` method of string objects, which right-aligns a string and pads it with spaces on the left.\\\\n\\\\nThere are similar methods, such as `ljust()` and `center()`. These methods do not write anything; they simply return a new string.\\\\n\\\\nAnother method, `zfill()`, pads a number on the left with zeros, as shown below:\\\\n\\\\n>>> '12'.zfill(5)\\\\n\\\\n'00012'\\\\n\\\\n>>> '-3.14'.zfill(7)\\\\n\\\\n'-003.14'\\\\n\\\\n>>> '3.14159265359'.zfill(5)\\\\n\\\\n'3.14159265359'\\\\n\\\\nThe basic usage of `str.format()` is as follows:\\\\n\\\\n>>> print('{}URL: "{}!"'.format('', 'www..com'))\\\\n\\\\nURL: "www..com!"\\\\n\\\\nThe brackets and the characters inside them (called format fields) will be replaced with the arguments passed to `format()`.\\\\n\\\\nThe numbers in the brackets refer to the position of the objects passed into `format()`, as shown below:\\\\n\\\\n>>> print('{0} and {1}'.format('Google', ''))\\\\n\\\\nGoogle and \\\\n\\\\n>>> print('{1} and {0}'.format('Google', ''))\\\\n\\\\n and Google\\\\n\\\\nIf keyword arguments are used in `format()`, their values will refer to the arguments using the specified names.\\\\n\\\\n>>> print('{name}URL: {site}'.format(name='', site='www..com'))\\\\n\\\\nURL: www..com\\\\n\\\\nPositional and keyword arguments can be combined arbitrarily:\\\\n\\\\n>>> print('Site list {0}, {1}, and {other}γ'.format('Google', '', other='Taobao'))\\\\n\\\\nSite list Google, , and Taobao.\\\\n\\\\n`!a` (using `ascii()`), `!s` (using `str()`), and `!r` (using `repr()`) can be used to convert the value before formatting:\\\\n\\\\n>>> import math\\\\n\\\\n>>> print('The value of constant PI is approximately: {}γ'.format(math.pi))\\\\n\\\\nThe value of constant PI is approximately: 3.141592653589793γ\\\\n\\\\n>>> print('The value of constant PI is approximately: {!r}γ'.format(math.pi))\\\\n\\\\nThe value of constant PI is approximately: 3.141592653589793γ\\\\n\\\\nAn optional `:` and format specifier can follow the field name. This allows for better formatting of the value. The following example rounds Pi to three decimal places:\\\\n\\\\n>>> import math\\\\n\\\\n>>> print('The value of constant PI is approximately {0:.3f}γ'.format(math.pi))\\\\n\\\\nThe value of constant PI is approximately 3.142γ\\\\n\\\\nPassing an integer after `:` ensures that the field has at least that width. This is useful for formatting tables.\\\\n\\\\n>>> table = {'Google': 1, '': 2, 'Taobao': 3}\\\\n\\\\n>>> for name, number in table.items():\\\\n\\\\n... print('{0:10} ==> {1:10d}'.format(name, number))\\\\n\\\\n...\\\\n\\\\nGoogle ==> 1\\\\n\\\\n ==> 2\\\\n\\\\nTaobao ==> 3\\\\n\\\\nIf you have a very long format string that you don't want to split up, it would be good to reference the variables by name instead of position.\\\\n\\\\nThe simplest way is to pass a dictionary and use square brackets `[]` to access the keys:\\\\n\\\\n>>> table = {'Google': 1, '': 2, 'Taobao': 3}\\\\n\\\\n>>> print(': {0[]:d}; Google: {0:d}; Taobao: {0:d}'.format(table))\\\\n\\\\n: 2; Google: 1; Taobao: 3\\\\n\\\\nThis can also be done by using the `**` prefix on the `table` variable:\\\\n\\\\n>>> table = {'Google': 1, '': 2, 'Taobao': 3}\\\\n\\\\n>>> print(': {:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table))\\\\n\\\\n: 2; Google: 1; Taobao: 3\\\\n\\\\n* * *\\\\n\\\\n## Old-Style String Formatting\\\\n\\\\nThe `%` operator can also be used for string formatting. It interprets the left argument much like a `sprintf()`-style format string, while the right argument is substituted, and then returns the formatted string. For example:\\\\n\\\\n>>> import math\\\\n\\\\n>>> print('The value of constant PI is approximately:%5.3fγ' % math.pi)\\\\n\\\\nThe value of constant PI is approximately: 3.142γ\\\\n\\\\nSince `str.format()` is a newer function, most Python code still uses the `%` operator. However, since this old-style formatting will eventually be removed from the language, it is recommended to use `str.format()` more often.\\\\n\\\\n* * *\\\\n\\\\n## Reading Keyboard Input\\\\n\\\\nPython provides the [input() built-in function](#) to read a line of text from standard input, which by default is the keyboard.\\\\n\\\\n## Example\\\\n\\\\n#!/usr/bin/python3\\\\n\\\\nstr = input("Please enter:");\\\\n\\\\nprint("The content you entered is: ", str)\\\\n\\\\nThis will produce the following result corresponding to the input:\\\\n\\\\nPlease enter:\\\\nThe content you entered is: \\\\n\\\\n* * *\\\\n\\\\n## Reading and Writing Files\\\\n\\\\nIn Python, file operations are performed using the `open()` function. This function returns a file object, which is used for subsequent read or write operations.\\\\n\\\\nThe basic syntax of `open()` is:\\\\n\\\\nopen(filename, mode)\\\\n* **filename:** The path to the file to be accessed (a string).\\\\n* **mode:** The file opening mode, which specifies how the file is to be opened (e.g., read-only, write, append, etc.). This parameter is optional and defaults to `r` (read-only).\\\\n\\\\nCommon file opening modes are as follows (it is recommended to focus on r / w / a):\\\\n\\\\n| Mode | Description |\\\\n| --- | --- |\\\\n| r | Opens a file for reading only (default mode). The file must exist, and the file pointer is at the beginning. |\\\\n| rb | Opens a file for reading only in binary format (e.g., images, videos). The file pointer is at the beginning. |\\\\n| r+ | Opens a file for both reading and writing. The file must exist, and the file pointer is at the beginning. |\\\\n| rb+ | Opens a file for both reading and writing in binary format. The file pointer is at the beginning. |\\\\n| w | Opens a file for writing only. If the file exists, it is **truncated**; if it does not exist, a new file is created. |\\\\n| wb | Opens a file for writing only in binary format. If the file exists, it is truncated; if it does not exist, a new file is created. |\\\\n| w+ | Opens a file for both reading and writing. If the file exists, it is truncated; if it does not exist, a new file is created. |\\\\n| wb+ | Opens a file for both reading and writing in binary format. If the file exists, it is truncated; if it does not exist, a new file is created. |\\\\n| a | Opens a file for appending. If the file exists, the write position is at the end of the file; if it does not exist, a new file is created. |\\\\n| ab | Opens a file for appending in binary format. The write position is at the end of the file; if it does not exist, a new file is created. |\\\\n| a+ | Opens a file for both reading and appending. The file pointer is at the end by default (append mode); if the file does not exist, a new file is created. |\\\\n| ab+ | Opens a file for both reading and appending in binary format. The file pointer is at the end by default; if the file does not exist, a new file is created. |\\\\n\\\\n**Note:** Adding `b` to the mode indicates that the file is operated on in binary mode, which is commonly used for handling non-text files like images and audio.\\\\n\\\\nThe following diagram summarizes these modes well:\\\\n\\\\n!(#)\\\\n\\\\n| Mode | r | r+ | w | w+ | a | a+ |\\\\n| --- | --- | --- | --- | --- | --- | --- |\\\\n| Read | + | + | | + | | + |\\\\n| Write | | + | + | + | + | + |\\\\n| Create | | | + | + | + | + |\\\\n| Truncate | | | + | + | | |\\\\n| Pointer at Beginning | + | + | + | + | | |\\\\n| Pointer at End | | | | | + | + |\\\\n\\\\nThe following example writes a string to the file `foo.txt`:\\\\n\\\\n## Example\\\\n\\\\n#!/usr/bin/python3\\\\n\\\\n# Open a file\\\\n\\\\nf = open("/tmp/foo.txt", "w")\\\\n\\\\nf.write("Python is a very good language.n Yes, indeed very good!!n")\\\\n\\\\n# Close the opened file\\\\n\\\\nf.close()\\\\n\\\\n* The first parameter is the filename to open.\\\\n* The second parameter describes how the file is used. `mode` can be `'r'` if the file is read-only, `'w'` for writing only (if a file with the same name exists, it will be deleted), and `'a'` for appending to the file; any data written will be automatically added to the end. `'r+'` is for both reading and writing. The `mode` parameter is optional; `'r'` will be the default.\\\\n\\\\nNow, open the file `foo.txt`, and it displays as follows:\\\\n\\\\n$ cat /tmp/foo.txt\\\\nPython is a very good language.\\\\nYes, indeed very good!!\\\\n\\\\n* * *\\\\n\\\\n## File Object Methods\\\\n\\\\nThe remaining examples in this section assume that a file object named `f` has been created.\\\\n\\\\n### f.read()\\\\n\\\\nTo read the contents of a file, call `f.read(size)`, which reads a certain amount of data and returns it as a string or bytes object.\\\\n\\\\n`size` is an optional numeric parameter. When `size` is omitted or negative, the entire content of the file is read and returned.\\\\n\\\\nThe following example assumes the file `foo.txt` already exists (as created in the example above):\\\\n\\\\n## Example\\\\n\\\\n#!/usr/bin/python3\\\\n\\\\n# Open a file\\\\n\\\\nf = open("/tmp/foo.txt", "r")\\\\n\\\\nstr = f.read()\\\\n\\\\nprint(str)\\\\n\\\\n# Close the opened file\\\\n\\\\nf.close()\\\\n\\\\nRunning the above program produces the following output:\\\\n\\\\nPython is a very good language.\\\\nYes, indeed very good!!\\\\n\\\\n### f.readline()\\\\n\\\\n`f.readline()` reads a single line from the file. A newline character (`'n'`) is left at the end of the string. If `f.readline()` returns an empty string, the end of the file has been reached.\\\\n\\\\n## Example\\\\n\\\\n#!/usr/bin/python3\\\\n\\\\n# Open a file\\\\n\\\\nf = open("/tmp/foo.txt", "r")\\\\n\\\\nstr = f.readline()\\\\n\\\\nprint(str)\\\\n\\\\n# Close the opened file\\\\n\\\\nf.close()\\\\n\\\\nRunning the above program produces the following output:\\\\n\\\\nPython is a very good language.\\\\n\\\\n### f.readlines()\\\\n\\\\n`f.readlines()` will return a list containing all the lines in the file.\\\\n\\\\nIf the optional `sizehint` parameter is set, it reads the specified number of bytes and splits them into lines.\\\\n\\\\n## Example\\\\n\\\\n#!/usr/bin/python3\\\\n\\\\n# Open a file\\\\n\\\\nf = open("/tmp/foo.txt", "r")\\\\n\\\\nstr = f.readlines()\\\\n\\\\nprint(str)\\\\n\\\\n# Close the opened file\\\\n\\\\nf.close()\\\\n\\\\nRunning the above program produces the following output:\\\\n\\\\n['Python is a very good language.n', 'Yes, indeed very good!!n']\\\\n\\\\nAnother way is to iterate over the file object and read each line:\\\\n\\\\n## Example\\\\n\\\\n#!/usr/bin/python3\\\\n\\\\n# Open a file\\\\n\\\\nf = open("/tmp/foo.txt", "r")\\\\n\\\\nfor line in f:\\\\n\\\\n print(line, end='')\\\\n\\\\n# Close the opened file\\\\n\\\\nf.close()\\\\n\\\\nRunning the above program produces the following output:\\\\n\\\\nPython is a very good language.\\\\nYes, indeed very good!!\\\\n\\\\nThis method is simple but does not provide good control. Since the processing mechanisms are different, it is best not to mix them.\\\\n\\\\n### f.write()\\\\n\\\\n`f.write(string)` writes the `string` to the file and returns the number of characters written.\\\\n\\\\n## Example\\\\n\\\\n#!/usr/bin/python3\\\\n\\\\n# Open a file\\\\n\\\\nf = open("/tmp/foo.txt", "w")\\\\n\\\\nnum = f.write("Python is a very good language.n Yes, indeed very good!!n")\\\\n\\\\nprint(num)\\\\n\\\\n# Close the opened file\\\\n\\\\nf.close()\\\\n\\\\nRunning the above program produces the following output:\\\\n\\\\n29\\\\n\\\\nIf you want to write something that is not a string, you need to convert it first:\\\\n\\\\n## Example\\\\n\\\\n#!/usr/bin/python3\\\\n\\\\n# Open a file\\\\n\\\\nf = open("/tmp/foo1.txt", "w")\\\\n\\\\nvalue = ('www..com', 14)\\\\n\\\\ns = str(value)\\\\n\\\\nf.write(s)\\\\n\\\\n# Close the opened file\\\\n\\\\nf.close()\\\\n\\\\nRunning the above program, open the `foo1.txt` file:\\\\n\\\\n$ cat /tmp/foo1.txt\\\\n('www..com', 14)\\\\n\\\\n### f.tell()\\\\n\\\\n`f.tell()` returns the current position of the file pointer (i.e., the file pointer's location). The file pointer indicates the byte offset from the beginning of the file. `f.tell()` returns an integer representing the current position of the file pointer.\\\\n\\\\n### f.seek()\\\\n\\\\nTo change the current position of the file pointer, you can use the `f.seek(offset, from_what)` function.\\\\n\\\\n`f.seek(offset, whence)` moves the file pointer to the specified position.\\\\n\\\\n`offset` indicates the offset relative to the `whence` parameter. The value of `from_what` is 0 for the beginning, 1 for the current position, and 2 for the end of the file. For example:\\\\n\\\\n* `seek(x, 0)`: Move `x` characters from the beginning of the file (the first character of the first line).\\\\n* `seek(x, 1)`: Move `x` characters forward from the current position.\\\\n* `seek(-x, 2)`: Move `x` characters backward from the end of the file.\\\\n\\\\nThe default value of `from_what` is 0, which is the beginning of the file. Here is a complete example:\\\\n\\\\n>>> f = open('/tmp/foo.txt', 'rb+')\\\\n\\\\n>>> f.write(b'0123456789abcdef')\\\\n\\\\n16\\\\n\\\\n>>> f.seek(5) # Move to the sixth byte of the file\\\\n\\\\n5\\\\n\\\\n>>> f.read(1)\\\\n\\\\nb'5'\\\\n\\\\n>>> f.seek(-3, 2) # Move to the third byte from the end of the file\\\\n\\\\n13\\\\n\\\\n>>> f.read(1)\\\\n\\\\nb'd'\\\\n\\\\n### f.close()\\\\n\\\\nIn text files (those opened without `b` in the mode), positioning is only relative to the beginning of the file.\\\\n\\\\nAfter you are done with a file, call `f.close()` to close it and release system resources. If you try to call the file again, an exception will be raised.\\\\n\\\\n>>> f.close()\\\\n\\\\n>>> f.read()\\\\n\\\\nTraceback (most recent call last):\\\\n\\\\n File "", line 1, in ?\\\\n\\\\nValueError: I/O operation on closed file\\\\n\\\\nWhen working with a file object, it is a good practice to use the `with` keyword. It ensures that the file is properly closed after the suite finishes, even if an exception is raised. It is also shorter than a `try`-`finally` block:\\\\n\\\\n>>> with open('/tmp/foo.txt', 'r') as f:\\\\n\\\\n... read_data = f.read()\\\\n\\\\n>>> f.closed\\\\n\\\\nTrue\\\\n\\\\nFile objects have other methods, such as `isatty()` and `truncate()`, but these are less commonly used.\\\\n\\\\n* * *\\\\n\\\\n## The pickle Module\\\\n\\\\nPython's `pickle` module implements basic data serialization and deserialization.\\\\n\\\\nThrough the serialization operation of the `pickle` module, we can save the information of objects running in a program to a file for permanent storage.\\\\n\\\\nThrough the deserialization operation of the `pickle` module, we can recreate the objects saved from the last program execution from a file.\\\\n\\\\nBasic interface:\\\\n\\\\npickle.dump(obj, file, [, protocol])\\\\nWith the `pickle` object, you can open the file for reading:\\\\n\\\\nx = pickle.load(file)\\\\n**Note:** Reads a string from `file` and reconstructs it into the original Python object.\\\\n\\\\n**file:** A file-like object with `read()` and `readline()` interfaces.\\\\n\\\\n## Example 1\\\\n\\\\n#!/usr/bin/python3\\\\n\\\\nimport pickle\\\\n\\\\n# Use the pickle module to save data objects to a file\\\\n\\\\ndata1 = {'a': [1, 2.0, 3, 4+6j],\\\\n\\\\n 'b': ('string', u'Unicode string'),\\\\n\\\\n 'c': None}\\\\n\\\\nselfref_list = [1, 2, 3]\\\\n\\\\nselfref_list.append(selfref_list)\\\\n\\\\noutput = open('data.pkl', 'wb')\\\\n\\\\n# Pickle dictionary using protocol 0.\\\\n\\\\npickle.dump(data1, output)\\\\n\\\\n# Pickle the list using the highest protocol available.\\\\n\\\\npickle.dump(selfref_list, output, -1)\\\\n\\\\noutput.close()\\\\n\\\\n## Example 2\\\\n\\\\n#!/usr/bin/python3\\\\n\\\\nimport pprint, pickle\\\\n\\\\n#Reconstruct Python objects from a file using the pickle module\\\\n\\\\npkl_file = open('data.pkl', 'rb')\\\\n\\\\ndata1 = pickle.load(pkl_file)\\\\n\\\\npprint.pprint(data1)\\\\n\\\\ndata2 = pickle.load(pkl_file)\\\\n\\\\npprint.pprint(data2)\\\\n\\\\npkl_file.close()
YouTip