Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the iUnip O related instructions in Python

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to use I/O-related instructions in Python". In daily operation, I believe many people have doubts about how to use I/O-related instructions in Python. Xiaobian consulted various materials and sorted out simple and easy operation methods. I hope to help you answer the doubts about "how to use I/O-related instructions in Python"! Next, please follow the small series to learn together!

Computer programs are used to perform tasks and are tools that meet human needs. With information input, the program can receive instructions and understand requirements; with information output, the results of the operation can be fed back to the user. In programming, information input operations are called Input, output operations are called Output, collectively referred to as Input/Output, abbreviated as I/O.

Compared to other languages, I/O operations in Python are simpler and more convenient, and basic input and output can be achieved through simple instructions. In addition, I/O does not only refer to typing and printing information, but also includes the input and output of files.

01 Input and print

1. input

The input function, when used for interactive information typing, is equivalent to a container in which the information entered by the user from the keyboard is stored first and then referenced by variables.

The input function can accept a variety of data types, including basic types such as number, str, and composite types such as list, tuple, dict, and set. When using the input function, you can add str within parentheses to prompt for input. Note that the input function in Python 3.x defaults all received data to str, as shown below.

Enter different data types

#Enter a number by Python default type number1 = input ('Please enter a number:')

Output:

Please enter a number: 1#Enter a str, by Python default type str1 = input ('Please enter a string:')

Output:

Please enter a string: 1#Enter a number and convert it to int type number2 = int(input ('please enter a number:'))

Output:

Please enter a number: 123#to view the output type of the above input print ('number 1, str1 and number2 are of type: \n', type(number1), type(str1), type(number2))

Output:

The types of number1, str1, and number2 are:

As you can see from the output, str1 is defaulted to str even though it is not str. To get the desired data type, type conversion must be done.

2. print

After assigning a variable, if you want to query the contents of the variable, just type the variable name and press Enter, which is called the output of the expression statement. Using print functions is a more popular way of outputting, allowing for a variety of output operations.

When using the print function for output operations, you can insert str in parentheses in the function to output specified text to the screen, such as printing "hello,world! "; to output the assigned variable, insert the variable name in parentheses in the print function.

The print function can also accept multiple strs, separated by commas. The print function prints each str in turn, outputting a space when a comma is encountered, so the output str is spelled. The print function can also calculate the result automatically. Run the "print(number1+number2)" statement, and the interpreter will automatically calculate the result of the addition and output it. The code for the print function is shown below.

print function application

# print function accepts multiple str prints ('I ', ' Ai','Zhonghua')

Output:

I love Chinese # print function calculates result print ('100 +200 =', 100 + 200) before printing

Output:

100+200 = 300

Format output is an important concept in computer output, mainly for str. Its operation mechanism is: use placeholders in str, replace placeholders with numbers or characters, reorganize str and output.

This output method is mainly to facilitate the modification of statements, reduce the workload of writing code, and contains automatic bit-taking, conversion and other functions. There are two ways to format output in Python: the "%+ formatter" method and the format function method.

The "%+ formatter" method is an older method of formatting output by adding the appropriate formatter after the percent sign (%) to place it, replacing it, and outputting it. Format characters in Python are shown below.

Python formatter

str

%s: string (display with str function)

%r: String (Display with repr function)

%c: single character

integer

%b: binary integer

%d: decimal integer

%i: decimal integer

%o: Octal integer

%x: hexadecimal integer

float

%e: exponent (base written as e)

%E: exponent (base written as E)

%f: floating point number

%F: floating point number

%g: exponent (e) or float (depending on display length)

As you can see, Python formatting can be used for str, integer, and float output, respectively. Format the output using the "%+ formatter" method, as shown below.

"%+ formatter" formats output

#Format string 'Zara' with %s and integer 20 print("My name is %s and I am %d years old! "%('Zara',20))

Output:

My name is Zara and I am 20 years old! format 16 with %d, octal representation of decimal integer 16 with %o print(octal representation of "%d is %o"%(16,16))

Output:

Octal of 16 is 20#Convert integer to float print with 3 decimal places reserved with %.3f ("23 to float number with 3 decimal places reserved %.3f"%(23))

Output:

23 converted to floating-point number with 3 decimal places 23.000

The format function is a more powerful tool for formatting output, collecting arbitrary sets of positional and keyword parameters and replacing placeholders in str with their values. This method uses curly brackets ({}) as a special character instead of %.{} can be used without parameters, with numerical numbers or with keyword numbers for placeholder and replacement. The first two belong to position replacement methods, and the latter belongs to keyword replacement methods.

The format function also supports formatters, as shown below.

format function formatter

'c': character. Convert integers to Unicode strings before printing

'b': binary. Output numbers based on 2

'o': octal. Output numbers in base 8

'd': decimal. Output numbers in base 10

'x': hexadecimal. Output numbers based on 16, with digits above 9 represented by lowercase letters

'e': Power symbol. Print numbers in scientific notation. Use 'e' for power

'g': general format. Output the values in fixed-point format, or print them in power form when the values are particularly large

'n': number. An integer is equivalent to'd'and a float is equivalent to' g'.

'%': percentage. Values multiplied by 100 are printed in fixed-point ('f ') format with a percent sign after the value

The basics of formatting output using the format function are shown below.

format function formats output

# format function output without arguments print("My name is {} and I am {} years old! ".format('Zara', 18))

Output:

My name is Zara and I am 20 years old! The format function is numerically numbered and out of order print("My name is {1} and I am {0} years old! ".format(18, 'Zara'))

Output:

My name is Zara and I am 20 years old! foemat function with keyword argument print("My name is {name} and I am {age} years old! ".format(age=18,name='Zara'))

Output:

My name is Zara and I am 20 years old! The format function formats numbers as binary numbers print("My name is {} and I am {:b} years old! ".format('Zara', 18))

Output:

My name is Zara and I am 10010 years old! 02 File I/O

1. open

The built-in function open opens a file and creates a file object to call. On the basis of opening the file, subsequent file read and write operations can be realized. The basic syntax for the open function is as follows:

open(filename, mode)

Common parameters of the open function and their descriptions are shown below.

Common parameters of open function and their descriptions

filename: Receive file name, indicating file name. no default

mode: Receive mode name, indicating file open mode. Default is read-only

filename indicates that it contains the name of the file you want to access. mode Determines the mode in which the file is opened. This parameter is optional. The default file access mode is read-only (r), which can take the following values.

File access patterns and their descriptions

r: Open the file read-only. The pointer to the file will be placed at the beginning of the file. this is the default mode

RB: Opens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. this is the default mode

r+: Open a file for reading and writing. The file pointer will be placed at the beginning of the file

RB+: Opens a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file

W: Open a file for writing only. overwrite the file if it already exists; create a new file if it does not exist

WB: Open a file in binary format for writing only. overwrite the file if it already exists; create a new file if it does not exist

w+: Open a file for reading and writing. overwrite the file if it already exists; create a new file if it does not exist

WB+: Opens a file in binary format for reading and writing. overwrite the file if it already exists; create a new file if it does not exist

A: Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file, that is, the new content will be written after the existing content; if the file does not exist, a new file will be created for writing

ab: Opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file, that is, the new content will be written after the existing content; if the file does not exist, a new file will be created for writing

A+: Open a file for reading and writing. If the file already exists, the file pointer is placed at the end of the file and the file opens in append mode; if the file does not exist, a new file is created for reading and writing

ab+: Opens a file in binary format for appending. If the file already exists, the file pointer is placed at the end of the file; if it does not exist, a new file is created for reading and writing

2. read

In Python, reading the contents of a file requires opening a file in read-only mode. You can pass in the file name and mode identifier with the open function, and then read the contents of the file with the read function. The read function reads the entire contents of an open file at once. The contents are read into memory and represented by a str object. The basic syntax of the read function is as follows:

f = open(filename, mode) f.read(size)

Common parameters of the read function and their descriptions are shown below.

Common parameters of read function and their descriptions

size: Receive number, indicating the number of characters read. Default is all characters in the file

size indicates the number of bytes to read from the file, and this method reads in from the beginning of the file, reading size bytes per call. If no size is passed in, the program tries to read as much content as possible, all the way to the end of the file.

Use the read function to read the test.txt file and print it, as shown below.

read function reads the test.txt file

#Open test.txt file in read-only mode data = open ('../ data/test.txt', 'r') #Read the contents of the file and save them to the content variable content = data.read () #Print the text content contained in the content variable print ('The contents of this text are:', content)

Output:

The text reads: Hello World!

3. write

In Python, writing to and reading from a file is similar: call open and pass in the identifier 'w' or 'wb' before writing to it using write. The basic syntax of the write function is as follows:

f = open(filename, mode) f.write(str)

Common parameters of the write function and their descriptions are shown below.

Common parameters of write function and their descriptions

str: Accepts any str that represents the text content being written. is blank by default

The write function writes any str to an open file. Note that str in Python can be binary data, not limited to text. To write something other than str, convert what you want to write to str first.

Writing to a file using the write function is as follows.

write function writes to a file

#Open a file web = open ('../ tmp/web.txt', ' w')#Convert content, write file value =www.tipdm.org 14) str_value = str(value) web.write(str_value) web.close() #Open text, read out written content web = open ('../ tmp/web.txt', 'r') content = web.read () print ('the content in this text is:', content)

Output:

The content in this text is: www.tipdm.org 14)

4. close

The close function flushes any unwritten information from the cache and closes the file so that it cannot be written. After using the file, it should be closed. The essence of closing the file is to separate the file pointer from the file. After closing, it is no longer possible to operate the file originally associated with it through the pointer.

If the file is not closed when it is used up, the file object will always occupy the operating system resources, and the operating system can open a limited number of files at the same time. When writing files, the data will occupy the operating system's memory, wait for the computer to be idle and then write slowly. The consequence of not calling the close function is that only part of the data may be written to disk, and other information will be lost.

The basic syntax for the close function is as follows:

fileObject.close()

Common parameters of the close function and their descriptions are shown below.

Common parameters of close function and their descriptions

fileObject: Receives the file name, indicating the file object being used. no default

At this point, the study of "how to use I/O-related instructions in Python" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report