Python input and output

Python input and output techniques

Python is a high-level programming language with clear and concise syntax and powerful functions. In Python programming, input and output are very important techniques. This article will introduce the commonly used input and output methods in Python, including how to use input functions, output functions, formatted output, and how to use other modules to achieve input and output.

Enter

In Python, we can use the input() function to implement user input. This function will ask the user to enter some text and save it in a variable. Here is a simple example:

name = input("Please enter your name:")
print("Hello," + name + "!")

In this example, the input() function will prompt the user to enter their name and store the result in the name variable. Then, the print() function outputs a greeting containing the name entered by the user.

The advantage of input functions is that the user can provide information directly to the program, which allows the program to be run interactively. This is very useful in many scenarios, such as asking the user to enter a password, register information, or select an action.

In addition, you can also use the sys.stdin.readline() method to implement input. This method will read a line of text from standard input. For example:

import sys
name = sys.stdin.readline().strip()
print("Hello," + name + "!")

The strip() method is used to remove the newline character at the end of the input line.

You can also use the argparse module to implement command line parameter parsing, for example:

import argparse
parser = argparse. ArgumentParser()
parser.add_argument('name', help='Enter your name')
args = parser. parse_args()
print("Hello," + args.name + "!")

In this example, the argparse module can parse command line arguments, the add_argument() method is used to add arguments, and the parse_args() method is used to parse arguments . Finally, the print() function will output a greeting containing the parsed parameters.

Output

In Python, we can use the print() function to output text. This function can accept one or more arguments and output them to the screen. Below is an example:

print("Hello, world!")

In this example, the print() function will output a simple greeting, “Hello, world!”.

In addition to simple text, the print() function can also output the value of a variable. For example:

name = "Alice"
print("Hello," + name + "!")

In this example, the print() function will output a greeting, which contains the value of a variable name.

In addition, you can also use the sys.stdout.write() method to achieve output, this method will write the specified string to the standard output. For example:

import sys
sys.stdout.write("Hello, world!\\
")

The write() method needs to manually add line breaks.

The advantage of the output function is that it can display the running results of the program to the user. This is very useful for debugging programs and verifying code correctness.

In addition, you can also use the logging module to achieve log output, for example:

import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG)
name = "Bob"
logging.debug("Hello," + name + "!")

In this example, the logging module is used to record the log, the basicConfig() method is used to configure the file name and level of the log output, and the debug() method Used to output DEBUG level log information.

Formatted output

Sometimes, we need to insert the value of a variable into a string. This can be achieved by formatting the output. In Python, we can use the % symbol to format strings. Below is an example:

name = "Bob"
age = 20
print("My name is %s, and I am %d years old this year." % (name, age))

In this example, %s and %d are placeholders for the format string. %s represents a string, and %d represents an integer. The parentheses following the % symbol contain variables to be inserted into the string.

In addition, Python also supports the use of {} and format() methods to achieve formatted output. For example:

name = "Bob"
age = 20
print("My name is {}, I am {} years old this year.".format(name, age))

{} represents a placeholder, and the format() method will fill the variables in the brackets into the placeholder in turn.

In addition, Python3.6 and above also support the use of f-string to achieve formatted output. For example:

name = "Bob"
age = 20
print(f"My name is {name}, I am {age} years old this year.")

f means f-string, which can directly embed variables in the string.

The advantage of formatted output is that you can more flexibly control the format of the output. This is very useful for scenarios that require fine-tuning the output format, such as outputting tables, reports, or logs.

Other input and output methods

In addition to the input and output methods described above, Python has other modules that can implement input and output. For example:

CSV module

The CSV module can be used to read and write CSV files. For example, we can read a CSV file and output its contents as follows:

import csv
with open('example.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='"')
    for row in reader:
        print(', '. join(row))

In this example, the csv module is used to read the CSV file, the open() function is used to open the file, and the delimiter parameter is used to specify the delimiter character, the quotechar parameter is used to specify the quote character. Finally, use the join() method to join the elements of each row for output.

JSON module

The JSON module can be used to read and write JSON files. For example, we can read a JSON file and output its contents as follows:

import json
with open('example.json', 'r') as f:
    data = json. load(f)
    print(data)

In this example, the json module is used to read the JSON file, the open() function is used to open the file, and the load() method is used to Load JSON data. Finally, use the print() function to output the data.

PyYAML module

The PyYAML module can be used to read and write YAML files. For example, we can read a YAML file and output its contents as follows:

import yaml
with open('example.yaml', 'r') as f:
    data = yaml.load(f, Loader=yaml.FullLoader)
    print(data)

In this example, the yaml module is used to read the YAML file, the open() function is used to open the file, and the load() method is used to Load YAML data. Finally, use the print() function to output the data.

Conclusion

In Python, input and output are very important technologies. Using the input() function allows us to get input from the user, and the print() function allows us to output text and variable values. In addition, there are sys.stdin.readline() and sys.stdout.write() methods, argparse module, logging module, csv module, json module and PyYAML module can realize input and output. In addition, we also learned how to use format strings to interpolate the value of variables, and use different methods to achieve input and output. Hope this article helps you!