preloader

Python101: 13. Output and Input

post thumb
Python
by Admin/ on 11 Jul 2021

Python101: 13. Output and Input

We’ve actually touched on Python’s input and output features in previous articles, so let’s learn more about them in this article.


1 Formatted output


Python outputs values in two ways: expression statements and print functions (the write method is used for output from file objects; for standard file output, see sys.stdout , detailed documentation).

If we want to convert the output value to a string, we can do so using the repr() or str() functions, where the repr() function produces an interpreter-readable expression and the str() function returns a user-readable expression.

If we don’t just want to print space-separated values, but want to control the formatting of the output, there are two ways to do it: one is to process the whole string yourself, and the other is to use str.format(), and the following describes the use of str.

1)Basic use

print('{} URL: "{}!"' .format('Python technology', 'codelink.ai'))
# Python technology URL: "codelink.ai"

The brackets and the characters inside them (called formatting fields) will be replaced by the arguments in format()

  1. The number in the parentheses is used to point to the position of the incoming object in format()
print('{0} and {1}'.format('Hello', 'Python'))
# Hello and Python
print('{0} {1}'.format('Hello', 'Python'))
# Hello Python
print('{1} {0}'.format('Hello', 'Python'))
# Python Hello
  1. If keyword arguments are used in format(), then their values will point to the arguments that use that name
print('{name} URL: {site}'.format(name='Python Technologies', site='codelink.ai'))
# Python technology URL: codelink.ai
  1. Location and keyword parameters can be arbitrarily combined
print('E-commerce sites {0}, {1}, {other}.' .format('taobao', 'jingdong', other='Pinduoduo'))
# e-commerce sites Taobao, Jingdong, Pinduoduo.
  1. Pass the dictionary in as a keyword parameter with the ** flag
"repr() shows quotes: {!a}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
  1. Optional : and format directives are allowed after the field name
# Convert PI to 3-digit precision
import math
print('The value of PI is approximately {0:.3f}.' .format(math.pi))
# The value of PI is approximately 3.142.
  1. Adding an integer to the : after the field will limit the minimum width of the field
table = {'Sjoerd': 123, 'Jack': 456, 'Dcab': 789}
for name, phone in table.items():
  print('{0:10} == {1:10d}'.format(name, phone))
# Jack == 456
# Dcab == 789
# Sjoerd == 123
  1. If there is a long formatted string and you do not want to split it you can pass in a dictionary and access its keys using the brackets ( [] ).
table = {'Sjoerd': 123, 'Jack': 456, 'Dcab': 789789789789}
print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ' 'Dcab: {0[Dcab]:d}'.format(table))
# Jack: 456; Sjoerd: 123; Dcab: 789789789789

It is also possible to pass this dictionary as a keyword parameter with the ** flag.

table = {'Sjoerd': 123, 'Jack': 456, 'Dcab': 789789789789}
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
# Jack: 456; Sjoerd: 123; Dcab: 789789789789

2 Read keyboard input


Python provides the input() built-in function to read a line of text from standard input, which by default is the keyboard. input() takes a Python expression as input and returns the result of the operation. Examples are as follows.

s = input("Please enter:")
print ("The input is: ", str)
# Please enter: Hello Python
# You entered: Hello Python

3 File reading and writing


The open() function returns a file object, the usual usage takes two arguments: open(filename, mode).

The first parameter filename is the name of the file to be accessed, the second parameter mode describes how to use the file (the possible values are mainly: ‘r’ reads the file; ‘w’ just writes the file, already existing files with the same name will be deleted; ‘a’ opens the file for appending, automatically adding to the end; ‘r+’ opens the file for reading and writing; ‘rb+’ opens a file in binary format (opens a file for reading and writing…) The mode parameter is optional and defaults to ‘r’.

3.1 File object methods

  • read()

To read the contents of the file, call read(size), with size as an optional parameter.

f = open('tmp.txt', 'r')
s = f.read(5)
print(s)
f.close()
# Hello
  • readline()

Reads a line with a line break of \n.

f = open('tmp.txt', 'r')
s = f.readline()
print(s)
f.close()
  • readlines()

Reads all lines contained in the file, with the optional parameter size.

f = open('tmp.txt', 'r')
s = f.readlines(1)
print(s)
f.close()
# ['Hello Python']
  • write()

write(string) Writes the contents of a string to a file.

f = open('tmp.txt', 'w')
num = f.write('Hello Python')
print(num)
f.close()
# 12
  • seek()

seek(offset, from_what) change the current position of the file. offset move distance; from_what start position, 0 means the beginning, 1 means the current position, 2 means the end, the default value is 0, that is, the beginning.

f = open('tmp.txt', 'rb+')
f.write(b'0123456789abcdef')
# Move to the 6th byte of the file
f.seek(5)
print(f.read())
# b'56789abcdef'
  • tell()

tell() returns the current position of the file object, which is the number of bytes counted from the beginning of the file.

f = open('tmp.txt', 'r')
f.seek(5)
print(f.tell())
5
  • close()

When you are done with a file, call close() to close the file and free up the system’s resources. You can also use the with keyword to handle file objects to automatically close files when they are used up.

with open('tmp.txt', 'r') as f:
  read_data = f.read()
print(f.closed)
# True

3.2 Manipulating json format data

  • json.dumps(obj) Serialization, conversion of obj to a string in json format.

  • json.dump(obj, fp) serialization, converting obj to a json formatted string, writing the string to a file.

  • json.loads(s) deserializes a json formatted string into a Python object.

  • json.load(fp) Deserialize, reads data from a file containing json format and deserializes it to a Python object.

import json
data = {'id':'1', 'name':'jhon', 'age':12}
with open('t.json', 'w') as f:
  json.dump(data, f)
with open("t.json", 'r') as f:
  d = json.load( f)
print(d)
# {'id': '1', 'name': 'jhon', 'age': 12}

Summary


This section gives you an introduction to Python input and output, and provides support for Python engineers to be able to choose the right input and output method for the actual situation.


Reference.

https://docs.python.org/zh-cn/3/library/string.html#formatspec

https://docs.pythontab.com/python/python3.5/inputoutput.html#tut-files

Python-100-days-day013

comments powered by Disqus