home PYTHONJAVA
 

Python3 input and output

In the previous chapters, we actually touched on Python input and output capabilities. In this section, Python inputs and outputs will be detailed.


Embellish output format

The two ways to exit Python values: the expression expression and the print () function.

The third way is to use the write () method of the file object. The standard output file can be referenced by sys.stdout.

If you want the output to be more versatile, you can use the str.format () function to format the output value.

If you want to convert the output value to a string, you can do it using the repr () or str () function.

  • The str (): function returns a form of user-readable expression.
  • repr (): produces a readable form of the interpreter.
  & gt; & gt; & gt;   s   =    " Ciao, welookups " 
  & gt; & gt; & gt;   str   (  s  )  
  "Ciao, welookups"  
  & gt; & gt; & gt;   repr   (  s  )  
  "'Ciao, welookups'"  
  & gt; & gt; & gt;   str   (  1   /   7  )  
  '0.14285714285714285'  
  & gt; & gt; & gt;   x   =     10     *     3.25  
  & gt; & gt; & gt;   y   =     200     *     200  
  & gt; & gt; & gt;   s   =     'x Valore di:'     +   repr   (  x  )     +     ', y Valore di:'     +   repr   (  y  )     +     '...'  
  & gt; & gt; & gt;     print   (  s  )  
x  Valore di:     32.5  ,   y   Valore di:   40000.   ..  
>>> # repr()La funzione può sfuggire a caratteri speciali in una stringa
... hello = 'hello, welookups\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, welookups\n'
>>> # repr() L'argomento può essere qualsiasi oggetto di Python
... repr((x, y, ('Google', 'welookups')))
"(32.5, 40000, ('Google', 'welookups'))"

There are two ways to generate a square and cubic table:

  & gt; & gt; & gt;     per   x   in   intervallo   (  1  ,     11  ):  
  ...     stampa   (  repr   (  x  ).   rjust   (  2  < span class = "pun">),   repr   (  x   *   x  ).   rjust   (  3  ),     end   =   ''  )  
  ...     # Notare l'uso della riga precedente 'end'      
     ...     stampa   (  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: In the first example, the spaces between each column are added by print ().

This example shows the rjust () method of a string object, which can hold the string to the right and fill the space to the left.

There are similar methods, such as ljust () and center (). These methods do not write anything, they only return a new string.

Another method, zfill (), will block 0 to the left of the number as follows:

  & gt; & gt;     '12 ' .   zfill   (  5  )  
  '00012'  
  & gt; & gt; & gt;     '- 3.14'  .   zfill   (  7  )  
  '- 003.14'  
  & gt; & gt; & gt;     '3.14159265359'  < span class = "pun">.   zfill   (  5  )  
  '3.14159265359'  

str.format () The basic use is as follows:

  & gt; & gt; & gt;     print   (  '{} place: "{}!"'   .   format   (  'place ...'  < span class = "pun">,     'www.welookups.com'  ))  

  Rookie tutorial URL:     "www.welookups.com! "  

The brackets and characters inside them (called formatted fields) will be replaced by the parameters in format ().

The number in brackets is used to indicate the position of the incoming object in format () as follows:

  & gt; & gt; & gt;     print   (  '{0} and {1}'  .   format   (  'Google'  ,     'welookups'  ))  
  Google     with     welookups  
  & gt; & gt; & gt;     print   (  '{1} and {0}'  .   format   (  'Google'  ,     'welookups'  ))  
  welookups     with     Google  

If keyword arguments are used in format (), their values will point to arguments that use that name.

  & gt; & gt; & gt;     print   (  '{name} place: {site}'  .   format   (  name   =   '菜鸟 教程'  ,   site   =   'www.welookups.com'  ))  
  Rookie tutorial website:   www  .   welookups  .   com  

The position and keyword parameters can be combined in any way:

Read and write files

Open() will return a file object with the basic syntax as follows:

open(filename, mode)
  • filename: A string value containing the name of the file you want to access.
  • mode: determines the mode in which the file is opened: read-only, write, append, etc. See the full list below for all possible values. This parameter is not mandatory and the default file access mode is read-only (r).

A complete list of open files in different modes:

ModeDescription
r< /td>Opens the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
rbOpen a file in binary format for read-only. The file pointer will be placed at the beginning of the file.
r+Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
wOpen a file for writing only. If the file already exists, open the file and start editing from the beginning, ie the original content will be deleted. If the file does not exist, create a new one.
wbOpen a file in binary format for writing only. If the file already exists, open the file and start editing from the beginning, ie the original content will be deleted. If the file does not exist, create a new one.
w+Open a file for reading and writing. If the file already exists, open the file and start editing from the beginning, ie the original content will be deleted. If the file does not exist, create a new one.
wb+Open a file in binary format for reading and writing. If the file already exists, open the file and start editing from the beginning, ie the original content will be deleted. If the file does not exist, create a new one.
aOpen a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file for writing.
abOpen a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file for writing.
a+Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. Append mode will be used when the file is opened. If the file does not exist, create a new file for reading and writing.
ab+Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

The following picture summarizes these patterns very well:

mode r r+ w w+ a a+
read + + + +
write + + + + +
create + + + +
cover + +
The pointer is at the beginning + + + +
Pointer at the end + +

The following example writes a string to the file foo.txt:

#!/usr/bin/python3

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

f.write( "Python It is a very good language. \nYes, it is very good!!\n" )

# Close open file
f.close()
  • The first parameter is the name of the file to open.
  • The second parameter describes how the file is used. Mode can be 'r' If the file is read-only, 'w' is only used for writing (if a file with the same name exists, it will be deleted), and 'a' is used for appending the file contents; any data written will be automatically added to the end . 'r+' is used for both reading and writing. The mode parameter is optional; 'r' will be the default.

At this point, open the file foo.txt and it looks like this:

$ cat /tmp< /span>/foo. TXT
Python  is a very good language. 
Yes, it’s really good!!

Method of file object

The remaining examples in this section assume that a file object called f has been created.

f.read()

To read the contents of a file, call f.read(size), which will read a certain amount of data and then return it as a string or byte object.

size is an optional numeric type parameter. When size is ignored or negative, everything in the file will be read and returned.

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

#!/usr/bin/python3

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

Str = f.read()
print(str)

# Close open files
f.close()

Execute the above program, the output is:

Python is a very good language. 
Yes, it’s really good!!

f.readline()

F.readline() will read a single line from the file. The newline character is '\n'. F.readline() If an empty string is returned, the last line has been read.

#!/usr/bin/python3

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

Str = f.readline()
print(str)

# Close open files
f.close()

Execute the above program, the output is:

Python is a very good language. 

f.readlines()

F.readlines() will return all the lines contained in the file.

If the optional parameter sizehint is set, the bytes of the specified length are read and the bytes are split by row.

#!/usr/bin/python3

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

Str = f.readlines()
print(str)

# Close open files
f.close()

Execute the above program, the output is:

['Python is a very good language. \n', 'Yes, it’s really good!!\ n']

Another way is to iterate over a file object and then read each line:

#!/usr/bin/python3

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

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

# Close open Text piece
f.close()

Execute the above program, the output is:

Python It is a very good language.
Yes, it is very good.!!

This method is simple, but does not provide a good control. Because the processing mechanism of the two is different, it is best not to mix them.

f.write()

f.write(string) Writes a string to a file and returns the number of characters written.

#!/usr/bin/python3

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

num = f.write( "Python It is a very good language. \nYes, it is very good.!!\n" )
print(num)
# Close open file
f.close()

Execute the above program, the output is:

29

If you want to write something that is not a string, you will need to convert it first:

#!/usr/bin/python3

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

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

# Close open file
f.close()

Execute the above program, open foo1.txt file:

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

f.tell()

F.tell() Returns the current location of the file object, which is the number of bytes since the beginning of the file.

f.seek()

If you want to change the current position of the file, you can use the f.seek(offset, from_what) function.

The value of from_what, if 0 is the beginning, if 1 is the current position, 2 is the end of the file, for example:

  • Seek(x,0) : Moves x characters from the starting position, which is the first character of the first line of the file
  • Seek(x,1) : means to move x characters backward from the current position
  • Seek(-x,2): means to move x characters from the end of the file

from_what The value defaults to 0, which is the beginning of the file. A complete example is given below:

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

f.close()

In a text file (there is no b in the mode of opening the file), it will only be positioned relative to the starting position of the file.

When you have finished processing a file, call f.close() to close the file and release the system's resources. If you try to call the file again, an exception will be thrown.

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

When working with a file object, using the with keyword is a great way. At the end, it will help you close the file correctly. And it's also shorter than the try - finally block:

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

There are other methods for file objects, such as isatty() and trucate(), but these are usually less useful.







welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.