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 specifically introduce 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; the standard output file can be referenced as `sys.stdout`.\\n\\nIf you want the output to be more varied, you can use the `str.format()` function to format the output values.\\n\\nIf you want to convert the output value to a string, you can use the `repr()` or `str()` functions.\\n\\n* **`str()`:** Returns a user-friendly representation of the value.\\n* **`repr()`:** Returns a representation that is more useful for the interpreter.\\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-justifies 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 with zeros on the left, 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 braces and the characters inside them (called format fields) will be replaced with the arguments from `format()`.\\n\\nThe numbers in the braces refer to the position of the object 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 argument with that name.\\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 formats 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 nice to reference the variables by name instead of position.\\n\\nThe simplest way is to pass in 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 passing the `table` dictionary as keyword arguments with the `**` prefix:\\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 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, `str.format()` should be used more.\\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 then used for subsequent reading or writing 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 mode in which the file is opened, specifying how it will be used (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 mastering r / w / a):\\n\\n| Mode | Description |\\n| --- | --- |\\n| r | Opens a file in read-only mode (default mode). The file must exist, and the file pointer is at the beginning. |\\n| rb | Opens a file in binary format for reading only (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 in binary format for both reading and writing. 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 in binary format for writing only. 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 in binary format for both reading and writing. If the file exists, it is truncated; if it does not exist, a new file is created. |\\n| a | Opens a file in append mode. If the file exists, the written content is appended to the end; if it does not exist, a new file is created. |\\n| ab | Opens a file in binary format for appending. The written content is appended to the end; if it does not exist, a new file is created. |\\n| a+ | Opens a file for both reading and writing. 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 in binary format for both reading and writing. 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` after the mode indicates that the file is operated 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 Start | + | + | + | + | | |\\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 be opened.\\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 content; 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\\nAt this point, opening the file `foo.txt` will display the following:\\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 ignored or negative, all contents of the file will be read and returned.\\n\\nThe following example assumes the file `foo.txt` already exists (as created in the previous example):\\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\\nExecuting 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, and is only omitted on the last line of the file. 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\\nExecuting 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` argument is present, instead of reading complete lines, the system reads enough bytes to contain at least that many bytes, and after converting those bytes to a line, it splits the line.\\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\\nExecuting the above program produces the following output:\\n\\n['Python is a very good language.n', 'Yes, indeed very good!!n']\\n\\nAnother way to iterate over a 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\\nExecuting 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 a good level of control. Because the underlying 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\\nExecuting the above program produces the following output:\\n\\n29\\n\\nIf you want to write something that is not a string, it will need to be converted 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\\nExecuting the above program and opening the file `foo1.txt`:\\n\\n$ cat /tmp/foo1.txt\\n('www..com', 14)\\n\\n### f.tell()\\n\\n`f.tell()` returns an integer that gives the current position of the file object in the file; it is the number of bytes from the beginning of the file.\\n\\n### f.seek()\\n\\nIf you want to change the current position of the file object, you can use the `f.seek(offset, from_what)` function.\\n\\n`f.seek(offset, whence)` moves the file pointer to a specified position.\\n\\n`offset` indicates the offset relative to the `whence` parameter. The value of `from_what` is 0 for the beginning of the file, 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.\\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 for `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 a `b` in the mode string), only seeks relative to the beginning of the file are allowed (with the exception of seeking to the very end with `seek(0, 2)`).\\n\\nWhen you are finished with a file, call `f.close()` to close it and free up any system resources taken up by the open file. After calling `f.close()`, any attempt to use the file object will automatically fail.\\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\\nIt is good practice to use the `with` keyword when dealing with file objects. It has the advantage that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using `with` is also much shorter than equivalent `try`-`finally` blocks:\\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 they are seldom used.\\n\\n* * *\\n\\n## The pickle Module\\n\\nThe Python `pickle` module implements a basic data serialization and deserialization system.\\n\\nThrough the serialization operation of the `pickle` module, we can save the information of objects running in the program to a file for permanent storage.\\n\\nThrough the deserialization operation of the `pickle` module, we can recreate the objects saved by the previous program from the file.\\n\\nBasic interface:\\n\\npickle.dump(obj, file, [,protocol])\\nWith the `pickle` object, the file can be opened for reading:\\n\\nx = pickle.load(file)\\n**Note:** Reads a string from `file` and reconstructs it as a 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