程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Fundamentals of Python: IO in Python

編輯:Python

brief introduction

IO It's input and output , Any program that wants to interact with the outside world , All need to use IO. be relative to java for ,Python Medium IO It's simpler , Easy to use .

This article will introduce in detail Python Medium IO operation .

linux Input and output

linux There are three standard inputs and outputs in , Namely STDIN,STDOUT,STDERR, The corresponding number is 0,1,2.

STDIN It's standard input , By default, information is read from the keyboard ;

STDOUT It's standard output , Output results to the terminal by default ;

STDERR It's standard error , Output results to the terminal by default .

That we use a lot 2>&1, Refers to the standard output 、 Standard error specified as the same output path .

Format output

python in , We can use print Method to output information .

Let's take a look at print Definition of function :

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Copy code 

print Function will objects print to file The specified text stream , With sep Separate and add... At the end end. sep, end, file and flush If there is , Then it must be given in the form of keyword parameters .

All non keyword parameters are converted to strings , And will be written to the stream , With sep Division , And add at the end end. sep and end All must be strings ; They can also be for None, This means using the default values . If not given objects, be print() Write only end.

file The parameter must be one with write(string) Object of method ; If the parameter does not exist or is None, Will use sys.stdout. Because the parameters to be printed are converted to text strings , therefore print() Cannot be used for binary mode file objects . For these objects , have access to file.write(...).

Whether the output is cached usually depends on file, But if flush The keyword parameter is true , The output stream is forced to refresh .

You can see print The output format is relatively simple . Let's look at how to enrich the output format .

f format

If you want to format a string , You can put... Before the beginning quotation mark of a string f or F.

In this case , We can introduce variable values directly into a string , Just put the variables in { and } In the middle .

>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'
Copy code 

In addition to the { } put Python Beyond variables , You can also put functions in it :

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
Copy code 

stay ':' Passing an integer after it can make the field the minimum character width . Easy column alignment :

>>> 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
Copy code 

{ } The variable in can also be followed by a conversion sign :'!a' Show application ascii() ,'!s' Show application str(), also '!r' Show application repr()

>>> 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'.
Copy code 

format format

besides ,str It comes with a powerful format function :

str.format(*args, **kwargs)
Copy code 

The string that calls this method can contain string literals or in curly braces {} The enclosed replacement fields , Each replacement field can contain a numeric index of the positional parameter , Or the name of a keyword parameter . Each replacement field in the returned string copy is replaced with the string value of the corresponding parameter .

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
Copy code 

Let's take another example of using indexes :

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
Copy code 

Look at an example of a keyword :

>>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
Copy code 

Let's take another example of combination :

>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
other='Georg'))
The story of Bill, Manfred, and Georg.
Copy code 

There are also examples of very complex combinations :

>>> 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
Copy code 

Or use '**' The symbol will table Pass... As a keyword parameter :

>>> 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
Copy code 

You can also use n type '{:n}' To format numbers :

>>> yes_votes = 42_572_654
>>> no_votes = 43_132_495
>>> percentage = yes_votes / (yes_votes + no_votes)
>>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes 49.67%'
Copy code 

repr and str

If we just want to Python Object to string , Then you can use repr() perhaps str(), str() A function is a representation used to return a human readable value , and repr() Is used to generate interpreter readable representations .

for instance :

>>> 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'))"
Copy code 

str Object also provides some ways to manually format strings :

>>> 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
Copy code 

String object str.rjust() Method to right align strings in a field of a given width by filling the left with spaces . A similar approach is str.ljust() and str.center().

If the input string is too long , They don't truncate strings , But return as is .

If you want to guarantee the length of the string , You can use slicing : x.ljust(n)[:n] .

You can also use str.zfill() To use 0 Fill string :

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

% formatting method

% It can also be used to format strings , Given 'string' % values, be string Medium % The instance will have zero or more values Element substitution . This operation is often called string interpolation .

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

Read and write files

python It's very easy to read files in , Use open() The method can .

open() Will return a file object . Let's take a look at its definition :

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Copy code 

The first parameter is the filename .

The second parameter is the file open mode , The available modes are :

character

significance

'r'

Read ( Default )

'w'

write in , And truncate the file first

'x'

Exclusive creation , Fail if file already exists

'a'

write in , If the file exists, append

'b'

Binary mode

't'

Text mode ( Default )

'+'

Open for update ( Read and write )

The default mode is 'r' .

Take a look at a open Examples of documents :

>>> f = open('workfile', 'w')
Copy code 

The file is open , Nature needs to be shut down , So we need to show the call f.close() Method :

>>> f.close()
Copy code 

Is there any similar java Medium try with resource The function of automatically closing files ?

We can use with, So after the file is used , Will be automatically turned off , Very easy to use .

>>> with open('workfile') as f:
... read_data = f.read()
>>> # We can check that the file has been automatically closed.
>>> f.closed
True
Copy code 

After the file is closed , If you want to read it again , You're going to report a mistake :

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

Method of file object

After getting the file object , We can call the methods in the file .

f.read(size) Will read some data and use it as a string ( In text mode ) Or byte string object ( In binary mode ) return .

size Is an optional numeric parameter . When size When omitted or negative , Will read and return the contents of the entire file ; When taking other values , Will read and return at most size Characters ( In text mode ) or size Bytes ( In binary mode ). If you have reached the end of the file ,f.read() Will return an empty string ('').

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
Copy code 

f.readline() Read a line from the file ; A newline (\n) At the end of the string , If the file doesn't end with a newline , Omit... At the last line of the file . If f.readline() Returns an empty string , It means that the end of the file has been reached , The blank line uses '\n' Express , The string contains only one newline character .

>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
Copy code 

There's a simpler way to read , It's just traversing through the file :

>>> for line in f:
... print(line, end='')
...
This is the first line of the file.
Second line of the file
Copy code 

If you want to read all the lines in the file as a list , You can also use list(f) or f.readlines().

f.write(string) Will be able to string The contents of are written to the file , And returns the number of characters written .

>>> f.write('This is a test\n')
15
Copy code 

If it's in text mode , So before writing to the file , You need to convert the object to text form , We can use str() To switch .

>>> value = ('the answer', 42)
>>> s = str(value) # convert the tuple to string
>>> f.write(s)
18
Copy code 

Use f.seek(offset, whence) You can locate the file pointer , Then the subsequent read operation will start from this position .

whence Of 0 The value indicates starting from the beginning of the file ,1 Indicates that the current file location is used ,2 Use the end of the file as a reference point . whence If omitted, the default value is 0, That is, the beginning of the file is used as the reference point .

>>> 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'
Copy code 

Use json

JSON It's a very convenient file format for information exchange . Let's see how to use JSON To convert an object to a string :

>>> import json
>>> json.dumps([1, 'simple', 'list'])
'[1, "simple", "list"]'
Copy code 

dumps Is to convert an object to json str. json One more dump Method , You can store objects directly into a file .

json.dump(x, f)
Copy code 

To parse from a file json character string , have access to load:

x = json.load(f)
Copy code 

JSON The key - The key in a value pair is always str Type of . When an object is transformed into JSON when , All the keys in the dictionary are cast to strings . The result of this is that the dictionary is converted into JSON Then it may not be equal to the original when it is converted back to the dictionary . let me put it another way , If x Keys with non strings , Then there are loads(dumps(x)) != x.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved