Hướng dẫn write function python - viết hàm python

Có một số cách để trình bày đầu ra của một chương trình; Dữ liệu có thể được in dưới dạng người có thể đọc được hoặc được ghi vào một tệp để sử dụng trong tương lai. Chương này sẽ thảo luận về một số khả năng.

7.1. Định dạng đầu ra fancierFancier Output Formatting¶

Cho đến nay, chúng tôi đã gặp hai cách viết các giá trị: các câu lệnh biểu thức và hàm

>>> 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'))"
7. .

Thông thường, bạn sẽ muốn kiểm soát nhiều hơn đối với định dạng đầu ra của mình hơn là chỉ đơn giản là in các giá trị phân tách không gian. Có một số cách để định dạng đầu ra.

  • Để sử dụng các chuỗi chữ được định dạng, hãy bắt đầu một chuỗi với

    >>> import math
    >>> print(f'The value of pi is approximately {math.pi:.3f}.')
    The value of pi is approximately 3.142.
    
    0 hoặc
    >>> import math
    >>> print(f'The value of pi is approximately {math.pi:.3f}.')
    The value of pi is approximately 3.142.
    
    1 trước dấu ngoặc kép mở hoặc dấu trích báo ba. Bên trong chuỗi này, bạn có thể viết một biểu thức python giữa các ký tự
    >>> import math
    >>> print(f'The value of pi is approximately {math.pi:.3f}.')
    The value of pi is approximately 3.142.
    
    2 và
    >>> import math
    >>> print(f'The value of pi is approximately {math.pi:.3f}.')
    The value of pi is approximately 3.142.
    
    3 có thể đề cập đến các biến hoặc giá trị theo nghĩa đen.formatted string literals, begin a string with
    >>> import math
    >>> print(f'The value of pi is approximately {math.pi:.3f}.')
    The value of pi is approximately 3.142.
    
    0 or
    >>> import math
    >>> print(f'The value of pi is approximately {math.pi:.3f}.')
    The value of pi is approximately 3.142.
    
    1 before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between
    >>> import math
    >>> print(f'The value of pi is approximately {math.pi:.3f}.')
    The value of pi is approximately 3.142.
    
    2 and
    >>> import math
    >>> print(f'The value of pi is approximately {math.pi:.3f}.')
    The value of pi is approximately 3.142.
    
    3 characters that can refer to variables or literal values.

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

  • Phương pháp

    >>> import math
    >>> print(f'The value of pi is approximately {math.pi:.3f}.')
    The value of pi is approximately 3.142.
    
    4 của chuỗi đòi hỏi nhiều nỗ lực thủ công hơn. Bạn vẫn sẽ sử dụng
    >>> import math
    >>> print(f'The value of pi is approximately {math.pi:.3f}.')
    The value of pi is approximately 3.142.
    
    2 và
    >>> import math
    >>> print(f'The value of pi is approximately {math.pi:.3f}.')
    The value of pi is approximately 3.142.
    
    3 để đánh dấu nơi một biến sẽ được thay thế và có thể cung cấp các chỉ thị định dạng chi tiết, nhưng bạn cũng cần cung cấp thông tin được định dạng.

    >>> 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%'
    

  • Cuối cùng, bạn có thể thực hiện tất cả các chuỗi tự xử lý bằng cách sử dụng các hoạt động cắt và nối chuỗi để tạo ra bất kỳ bố cục nào bạn có thể tưởng tượng. Loại chuỗi có một số phương thức thực hiện các hoạt động hữu ích cho các chuỗi đệm theo chiều rộng cột nhất định.

Khi bạn không cần đầu ra ưa thích nhưng chỉ muốn hiển thị nhanh một số biến cho mục đích gỡ lỗi, bạn có thể chuyển đổi bất kỳ giá trị nào thành một chuỗi với các hàm

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
7 hoặc
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
8.

Hàm

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
8 có nghĩa là trả về các biểu diễn của các giá trị khá có thể đọc được, trong khi
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
7 có nghĩa là tạo ra các biểu diễn có thể được trình thông dịch đọc (hoặc sẽ buộc
>>> 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
1 nếu không có cú pháp tương đương). Đối với các đối tượng không có một đại diện cụ thể cho tiêu dùng của con người,
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
8 sẽ trả về giá trị tương tự như
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
7. Nhiều giá trị, chẳng hạn như số hoặc cấu trúc như danh sách và từ điển, có cùng một biểu diễn bằng cách sử dụng một trong hai hàm. Chuỗi, đặc biệt, có hai đại diện riêng biệt.

Vài ví dụ:

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

Mô -đun

>>> 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
4 chứa một lớp
>>> 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
5 cung cấp một cách khác để thay thế các giá trị thành các chuỗi, sử dụng trình giữ chỗ như
>>> 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
6 và thay thế chúng bằng các giá trị từ từ điển, nhưng cung cấp ít kiểm soát định dạng hơn nhiều.

7.1.1. Chuỗi được định dạng theo nghĩa chữFormatted String Literals¶

Các chuỗi chữ được định dạng (còn được gọi là F-Strings viết tắt) cho phép bạn bao gồm giá trị của các biểu thức python bên trong một chuỗi bằng cách tiền tố chuỗi với

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
0 hoặc
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
1 và viết các biểu thức là
>>> 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
9. (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
0 or
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
1 and writing expressions as
>>> 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
9.

Một định dạng định dạng tùy chọn có thể theo biểu thức. Điều này cho phép kiểm soát nhiều hơn về cách giá trị được định dạng. Các ví dụ sau đây làm tròn Pi đến ba vị trí sau thập phân:

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

Vượt qua một số nguyên sau

>>> 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'.
0 sẽ khiến trường đó có số lượng ký tự tối thiểu. Điều này rất hữu ích để làm cho các cột xếp hàng.

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

Các sửa đổi khác có thể được sử dụng để chuyển đổi giá trị trước khi nó được định dạng.

>>> 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'.
1 áp dụng
>>> 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'.
2,
>>> 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'.
3 áp dụng
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
8 và
>>> 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'.
5 áp dụng
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
7:

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

Bộ xác định

>>> 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'.
7 có thể được sử dụng để mở rộng biểu thức sang văn bản của biểu thức, một dấu bằng, sau đó biểu diễn của biểu thức được đánh giá:

>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'

Xem các biểu thức tự ghi chép để biết thêm thông tin về trình xác định

>>> 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'.
7. Để biết tham khảo về các thông số kỹ thuật định dạng này, hãy xem Hướng dẫn tham khảo cho ngôn ngữ nhỏ Đặc tả Định dạng.self-documenting expressions for more information on the
>>> 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'.
7 specifier. For a reference on these format specifications, see the reference guide for the Format Specification Mini-Language.

7.1.2. Phương thức định dạng chuỗi ()The String format() Method¶

Việc sử dụng cơ bản của phương pháp

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
4 trông như thế này:

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"

Các dấu ngoặc và ký tự trong chúng (được gọi là trường định dạng) được thay thế bằng các đối tượng được truyền vào phương thức

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
4. Một số trong ngoặc có thể được sử dụng để chỉ vị trí của đối tượng được chuyển vào phương thức
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
4.

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

Nếu các đối số từ khóa được sử dụng trong phương thức

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
4, các giá trị của chúng được đề cập bằng cách sử dụng tên của đối số.

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

Đối số vị trí và từ khóa có thể được kết hợp một cách tùy ý:

>>> 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%'
0

Nếu bạn có một chuỗi định dạng thực sự dài mà bạn không muốn chia tách, sẽ thật tuyệt nếu bạn có thể tham khảo các biến được định dạng theo tên thay vì theo vị trí. Điều này có thể được thực hiện bằng cách đơn giản là vượt qua Dict và sử dụng dấu ngoặc vuông

>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'
3 để truy cập các phím.

>>> 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%'
1

Điều này cũng có thể được thực hiện bằng cách truyền từ điển

>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'
4 làm đối số từ khóa với ký hiệu
>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'
5.

>>> 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%'
2

Điều này đặc biệt hữu ích khi kết hợp với hàm tích hợp

>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'
6, trả về một từ điển chứa tất cả các biến cục bộ.

Ví dụ, các dòng sau đây tạo ra một tập hợp các cột được căn chỉnh gọn gàng cho các số nguyên và hình vuông và hình khối của chúng:

>>> 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%'
3

Để biết tổng quan đầy đủ về định dạng chuỗi với

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
4, hãy xem Cú pháp Chuỗi định dạng.Format String Syntax.

7.1.3. Định dạng chuỗi thủ côngManual String Formatting¶

Ở đây, cùng một bảng hình vuông và hình khối, được định dạng bằng tay:

>>> 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%'
4

(Lưu ý rằng một không gian giữa mỗi cột được thêm vào bằng cách

>>> 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'))"
7 hoạt động: Nó luôn thêm khoảng trắng giữa các đối số của nó.)

Phương pháp

>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'
9 của các đối tượng chuỗi phải chuyển đổi một chuỗi trong một trường có chiều rộng nhất định bằng cách đệm nó với khoảng trắng ở bên trái. Có các phương pháp tương tự
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
0 và
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
1. Các phương thức này không viết bất cứ điều gì, chúng chỉ trả lại một chuỗi mới. Nếu chuỗi đầu vào quá dài, chúng không cắt nó, nhưng trả lại nó không thay đổi; Điều này sẽ làm rối tung ra cột của bạn nhưng điều đó thường tốt hơn so với giải pháp thay thế, điều này sẽ nói dối về một giá trị. .

Có một phương pháp khác,

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
3, trong đó đệm một chuỗi số ở bên trái với số không. Nó hiểu về các dấu hiệu cộng và trừ:

>>> 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%'
5

7.1.4. Định dạng chuỗi cũOld string formatting¶

Toán tử % (modulo) cũng có thể được sử dụng cho định dạng chuỗi. Cho

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
4, các trường hợp
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
5 trong
>>> 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
4 được thay thế bằng 0 hoặc nhiều yếu tố của
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
7. Hoạt động này thường được gọi là nội suy chuỗi. Ví dụ:

>>> 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%'
6

Thêm thông tin có thể được tìm thấy trong phần định dạng chuỗi kiểu printf.printf-style String Formatting section.

7.2. Đọc và viết các tập tinReading and Writing Files¶

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
8 Trả về một đối tượng tệp và được sử dụng phổ biến nhất với hai đối số vị trí và một đối số từ khóa:
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
9file object, and is most commonly used with two positional arguments and one keyword argument:
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
9

>>> 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%'
7

Đối số đầu tiên là một chuỗi chứa tên tệp. Đối số thứ hai là một chuỗi khác chứa một vài ký tự mô tả cách sử dụng tệp. Chế độ có thể là

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
0 khi tệp sẽ chỉ được đọc,
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
1 chỉ để viết (một tệp hiện có có cùng tên sẽ bị xóa) và
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
2 mở tệp để thêm; Bất kỳ dữ liệu nào được ghi vào tệp được tự động thêm vào cuối.
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
3 mở tập tin cho cả đọc và viết. Đối số chế độ là tùy chọn;
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
0 sẽ được giả định nếu nó bị bỏ qua.

Thông thường, các tệp được mở trong chế độ văn bản, điều đó có nghĩa là, bạn đọc và ghi các chuỗi từ và vào tệp, được mã hóa trong một mã hóa cụ thể. Nếu mã hóa không được chỉ định, mặc định phụ thuộc vào nền tảng (xem

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
8). Bởi vì UTF-8 là tiêu chuẩn de-facto hiện đại,
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
6 được khuyến nghị trừ khi bạn biết rằng bạn cần sử dụng một mã hóa khác. Lắp đặt
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
7 vào chế độ mở tệp ở chế độ nhị phân. Dữ liệu chế độ nhị phân được đọc và viết dưới dạng đối tượng
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
8. Bạn không thể chỉ định mã hóa khi mở tệp ở chế độ nhị phân.

Trong chế độ văn bản, mặc định khi đọc là chuyển đổi các kết thúc dòng dành riêng cho nền tảng (

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
9 trên Unix,
>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
0 trên Windows) thành
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
9. Khi viết ở chế độ văn bản, mặc định là chuyển đổi các lần xuất hiện của
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
9 trở lại kết thúc dòng cụ thể của nền tảng. Việc sửa đổi hậu trường này đối với dữ liệu tệp là tốt cho các tệp văn bản, nhưng sẽ tham nhũng dữ liệu nhị phân như thế trong các tệp
>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
3 hoặc
>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
4. Hãy rất cẩn thận để sử dụng chế độ nhị phân khi đọc và viết các tệp đó.

Đó là thực tế tốt để sử dụng từ khóa

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
5 khi xử lý các đối tượng tệp. Ưu điểm là tệp được đóng đúng sau khi bộ của nó kết thúc, ngay cả khi một ngoại lệ được nâng lên tại một số điểm. Sử dụng
>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
5 cũng ngắn hơn nhiều so với việc viết tương đương ________ 97 -________ 98 khối:

>>> 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%'
8

Nếu bạn không sử dụng từ khóa

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
5, thì bạn nên gọi
>>> 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%'
00 để đóng tệp và ngay lập tức giải phóng bất kỳ tài nguyên hệ thống nào được sử dụng bởi nó.

Cảnh báo

Gọi

>>> 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%'
01 mà không sử dụng từ khóa
>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
5 hoặc gọi
>>> 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%'
00 có thể dẫn đến các đối số của
>>> 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%'
01 không được ghi hoàn toàn vào đĩa, ngay cả khi chương trình thoát ra thành công.might result in the arguments of
>>> 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%'
01 not being completely written to the disk, even if the program exits successfully.

Sau khi một đối tượng tệp được đóng, bằng câu lệnh

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
5 hoặc bằng cách gọi
>>> 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%'
00, cố gắng sử dụng đối tượng tệp sẽ tự động bị lỗi.

>>> 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%'
9

7.2.1. Phương thức của đối tượng tệpMethods of File Objects¶

Phần còn lại của các ví dụ trong phần này sẽ cho rằng một đối tượng tệp được gọi là

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
0 đã được tạo.

Để đọc nội dung của tệp, hãy gọi

>>> 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%'
08, đọc một số lượng dữ liệu và trả về nó dưới dạng chuỗi (ở chế độ văn bản) hoặc đối tượng byte (ở chế độ nhị phân). Kích thước là một đối số số tùy chọn. Khi kích thước bị bỏ qua hoặc âm, toàn bộ nội dung của tệp sẽ được đọc và trả về; Đó là vấn đề của bạn nếu tệp lớn gấp đôi so với bộ nhớ máy của bạn. Mặt khác, ở hầu hết các ký tự kích thước (ở chế độ văn bản) hoặc byte kích thước (ở chế độ nhị phân) được đọc và trả về. Nếu kết thúc của tệp đã đạt được,
>>> 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%'
09 sẽ trả về một chuỗi trống (
>>> 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%'
10).

>>> 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'))"
0

>>> 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%'
11 đọc một dòng duy nhất từ ​​tệp; Một ký tự dòng mới (
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
9) bị bỏ lại ở cuối chuỗi và chỉ bị bỏ qua trên dòng cuối cùng của tệp nếu tệp không kết thúc trong một dòng mới. Điều này làm cho giá trị trả lại không rõ ràng; Nếu
>>> 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%'
11 trả về một chuỗi trống, phần cuối của tệp đã đạt được, trong khi một dòng trống được biểu thị bằng
>>> 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%'
14, một chuỗi chỉ chứa một dòng mới.

>>> 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'))"
1

Để đọc các dòng từ một tệp, bạn có thể lặp qua đối tượng tệp. Đây là bộ nhớ hiệu quả, nhanh chóng và dẫn đến mã đơn giản:

>>> 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'))"
2

Nếu bạn muốn đọc tất cả các dòng của một tệp trong danh sách, bạn cũng có thể sử dụng

>>> 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%'
15 hoặc
>>> 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%'
16.

>>> 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%'
17 ghi nội dung của chuỗi vào tệp, trả về số lượng ký tự được viết.

>>> 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'))"
3

Các loại đối tượng khác cần được chuyển đổi - thành một chuỗi (ở chế độ văn bản) hoặc đối tượng byte (ở chế độ nhị phân) - trước khi viết chúng:

>>> 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'))"
4

>>> 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%'
18 Trả về một số nguyên cung cấp cho đối tượng tệp vị trí hiện tại trong tệp được biểu thị bằng số byte từ đầu tệp khi ở chế độ nhị phân và số mờ khi ở chế độ văn bản.

Để thay đổi vị trí đối tượng tệp, hãy sử dụng

>>> 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%'
19. Vị trí được tính toán từ việc thêm bù vào một điểm tham chiếu; Điểm tham chiếu được chọn bởi đối số WHENCE. Giá trị từ 0 đo từ đầu tệp, 1 sử dụng vị trí tệp hiện tại và 2 sử dụng phần cuối của tệp làm điểm tham chiếu. từ đó có thể được bỏ qua và mặc định là 0, sử dụng đầu của tệp làm điểm tham chiếu.

>>> 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'))"
5

Trong các tệp văn bản (những tệp được mở mà không có

>>> 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%'
20 trong chuỗi chế độ), chỉ tìm kiếm liên quan đến đầu tệp được cho phép (ngoại lệ đang tìm kiếm kết thúc tệp với
>>> 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%'
21) và các giá trị bù hợp lệ duy nhất là các giá trị được trả về từ
>>> 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%'
18, hoặc không. Bất kỳ giá trị bù khác tạo ra hành vi không xác định.

Các đối tượng tệp có một số phương thức bổ sung, chẳng hạn như

>>> 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%'
23 và
>>> 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%'
24 ít được sử dụng ít thường xuyên hơn; Tham khảo tài liệu tham khảo thư viện để biết hướng dẫn đầy đủ về các đối tượng tệp.

7.2.2. Lưu dữ liệu có cấu trúc với ________ 125¶Saving structured data with >>> 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%' 25¶

Chuỗi có thể dễ dàng được ghi và đọc từ một tập tin. Các số cần thêm một chút nỗ lực, vì phương thức

>>> 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%'
26 chỉ trả về chuỗi, sẽ phải được chuyển đến một hàm như
>>> 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%'
27, có một chuỗi như
>>> 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%'
28 và trả về giá trị số của nó 123. Khi bạn muốn lưu các loại dữ liệu phức tạp hơn như Danh sách và từ điển lồng nhau, phân tích cú pháp và tuần tự bằng tay trở nên phức tạp.

Thay vì để người dùng liên tục viết và gỡ lỗi mã để lưu các loại dữ liệu phức tạp vào các tệp, Python cho phép bạn sử dụng định dạng trao đổi dữ liệu phổ biến có tên là JSON (ký hiệu đối tượng JavaScript). Mô -đun tiêu chuẩn được gọi là

>>> 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%'
25 có thể lấy hệ thống phân cấp dữ liệu Python và chuyển đổi chúng thành các biểu diễn chuỗi; Quá trình này được gọi là tuần tự hóa. Tái tạo dữ liệu từ biểu diễn chuỗi được gọi là khử Deserializing. Giữa tuần tự hóa và giải phóng hóa, chuỗi đại diện cho đối tượng có thể đã được lưu trữ trong một tệp hoặc dữ liệu hoặc gửi qua kết nối mạng đến một số máy xa.

Ghi chú

Định dạng JSON thường được sử dụng bởi các ứng dụng hiện đại để cho phép trao đổi dữ liệu. Nhiều lập trình viên đã quen thuộc với nó, điều này làm cho nó trở thành một lựa chọn tốt cho khả năng tương tác.

Nếu bạn có một đối tượng

>>> 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%'
30, bạn có thể xem biểu diễn chuỗi JSON của nó bằng một dòng mã đơn giản:

>>> 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'))"
6

Một biến thể khác của hàm

>>> 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%'
31, được gọi là
>>> 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%'
32, chỉ đơn giản là tuần tự hóa đối tượng thành tệp văn bản. Vì vậy, nếu
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
0 là một đối tượng tệp văn bản được mở để viết, chúng ta có thể làm điều này:text file. So if
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
0 is a text file object opened for writing, we can do this:

Để giải mã lại đối tượng, nếu

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
0 là một tệp nhị phân hoặc đối tượng tệp văn bản đã được mở để đọc:binary file or text file object which has been opened for reading:

Ghi chú

Định dạng JSON thường được sử dụng bởi các ứng dụng hiện đại để cho phép trao đổi dữ liệu. Nhiều lập trình viên đã quen thuộc với nó, điều này làm cho nó trở thành một lựa chọn tốt cho khả năng tương tác.text file for both of reading and writing.

Nếu bạn có một đối tượng

>>> 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%'
30, bạn có thể xem biểu diễn chuỗi JSON của nó bằng một dòng mã đơn giản:

Một biến thể khác của hàm

>>> 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%'
31, được gọi là
>>> 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%'
32, chỉ đơn giản là tuần tự hóa đối tượng thành tệp văn bản. Vì vậy, nếu
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
0 là một đối tượng tệp văn bản được mở để viết, chúng ta có thể làm điều này:

Để giải mã lại đối tượng, nếu

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
0 là một tệp nhị phân hoặc đối tượng tệp văn bản đã được mở để đọc:

Các tệp JSON phải được mã hóa trong UTF-8. Sử dụng

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
6 khi mở tệp JSON làm tệp văn bản cho cả đọc và viết.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.