Python file input and output
This article takes a .txt file as an example of how Python reads content from and writes content to a .txt file.
File contents:
The dog barks at the sound of water, and the peach blossoms are thick with rain.
When the trees are deep, you can see the deer, and the stream doesn't hear the bell at noon.
The wild bamboos are divided into green mist, and the flying spring hangs on the blue peak.
No one knows where to go, leaning sadly on two or three pines.
File Input
Read the file:
open(filename, mode)
open returns a file object.
The first argument is a string containing the filename.
The second parameter describes the usage mode of the document. mode='r' means read-only, mode='w' means write-only, mode='r+' means readable and writable, and mode='a ' means open the document and attach the content to be written to the end of the document, will not delete the existing content of the document.
The default mode is 'r'.
poem = open('./', 'r') print(poem) # Output # <_io.TextIOWrapper name='./' mode='r' encoding='UTF-8'>
poem = open('./', 'r') print(list(poem)) # Output # ['The dog barks at the sound of water, and the peach blossoms are thick with rain. \n', 'When the trees are deep, I see deer, and when the stream is at noon, I don't hear the bell. \n', 'The wild bamboos part the green mist, and the flying springs hang over the blue peaks. \n', 'No one knows where to go, leaning sadly on two or three pines. \n']
Usually we use the with keyword to read file objects. The with keyword can automatically close the file at the end of the with statement to avoid occupying computer memory resources all the time.
with open('./', 'r') as f: d = () print(d) print() # Output # The dog barks at the sound of the water, the peach blossoms are thick with rain. # # When the trees are deep, I see deer, and the streams don't hear the bells at noon. # # The wild bamboos are green and misty, the flying springs hang on the blue peaks. # # No one knows where to go, leaning on two or three pines. # # True
In addition to reading everything in the file, we can also read the file line by line.
with open('./') as f: for line in f: print(line) # Output # The dog barks at the sound of the water, the peach blossoms are thick with rain. # # When the trees are deep, I see deer, and the streams don't hear the bells at noon. # # The wild bamboos are green and misty, the flying springs hang on the blue peaks. # # lit. no one knows where to go (idiom); no one knows where to go,leaning on two or three pines with anxiety。
Because of the newline character at the end of each line, there is a blank line between each line. This can be verified:
with open('./') as f: d = () print(d) # Output # ['The dog barks at the sound of water, and the peach blossoms are thick with rain. \n', 'When the trees are deep, I see deer, and when the stream is at noon, I don't hear the bell. \n', 'The wild bamboos part the green mist, and the flying springs hang over the blue peaks. \n', 'No one knows where to go, leaning sadly on two or three pines. \n']
We can remove newlines at the end of a string with the ([chars]) function.
strip() function can remove the specified characters or strings at the beginning and end of the string, the parameter chars specifies the set of characters to be removed.
If not specified, it defaults to spaces or newlines.
But strip() can only delete the beginning or end character or string, not the middle part of the character.
with open('./') as f: for line in f: print(()) # Output # The dog barks at the sound of the water, the peach blossoms are thick with rain. # # When the trees are deep, I see deer, and the streams don't hear the bells at noon. # # The wild bamboos are green and misty, the flying springs hang on the blue peaks. # # lit. no one knows where to go (idiom); no one knows where to go,leaning on two or three pines with anxiety。
Because strings are immutable objects, the strip() function does not perform the deletion directly in the original string, but takes the string after deleting the first and last characters and returns it as a new object.
It can be verified:
a = ' special ' # Create a string object and point the variable a to it print(id(a)) # Print a's address in memory a = () # Take the string after removing the first and last spaces as a new object and point a to it print(id(a)) # Type the address of a string in memory # Output # 140251513494960 # 140251513470680
As you can see, the addresses of the strings before and after the deletion are not the same, indicating that they are different objects.
file output
with open('./', 'a') as f: ('Author: Li Bai\n') with open('./', 'r') as f: for line in f: print(()) # Output # The dog barks at the sound of the water, the peach blossoms are thick with rain. # # When the trees are deep, I see deer, and the streams don't hear the bells at noon. # # The wild bamboos are green and misty, the flying springs hang on the blue peaks. # # No one knows where to go, leaning on two or three pines. # # author:Li Bai (701-762), famous Tang Dynasty poet
Python Input-Output Syntax
Python is an easy-to-learn, powerful programming language. It provides efficient high-level data structures and also allows for simple and effective object-oriented programming. python's elegant syntax and dynamic typing, as well as the interpreted nature of the language, make it an ideal language for writing scripts and rapid application development on most platforms. Here we will introduce the input and output usage of python and give a few examples to learn more about it.
Inputs and outputs
1. Output
- Use the print() function for output in Python.
- Output strings can be enclosed in single or double quotes;
- Outputting variables can be done without quotes;
- When variables and strings are output at the same time or multiple variables are output at the same time, it is necessary to separate each item with ",".
print outputs newlines by default, but you need to add end="" to the end of the variable if you want it to be non-newline.
Example: Use the print() function to output data.
print("This is a sample output.") # print() function using double quotes output example url = '' # Create the variable url, assign the value '' print('Our web address is ', url) # print()Functions use single quotes to output variablesurl
The results of the run are as follows.
2. Input
Python provides the input() function for getting the characters entered by the user's keyboard.
The input() function pauses the program and waits for the user to enter data. When the user input is obtained, Python stores it as a string in a variable for later use.
Example: Use the input() function to implement input.
password = input("Please enter the password:") # Input data assigned to variable password print('The password you just entered is:', password) # output data
The results of the run are as follows.
case (law)
Example 1: Finding the sum of two numbers
Write a program that requires input of two integers and outputs the sum of the two numbers.
(1) The int() function can be used to convert the input string to integer data.
(2) The float() function can be used to convert strings to floating-point data.
a = input("Please enter the first integer:") # Enter the value of variable a b = input("Please enter a second integer:") # Enter the value of variable b a = int(a) # Convert variable a to an integer b = int(b) # Convert variable b to an integer c = a + b # Add two numbers and assign them to c print("The sum of two numbers is:", c) # exportscvalue of
The results of the run are as follows.
Example 2: Finding the area of a triangle
Write a program that requires the input of three sides of a triangle (assuming that the given three sides satisfy the condition for forming a triangle: the sum of any two sides is greater than the third side), calculates the area of the triangle and outputs it.
import math # Import the math module a = int(input("Please enter the first side of the triangle:")) # Enter the first edge and convert it to an integer b = int(input("Please enter the second side of the triangle:")) # Enter the second edge and convert it to an integer c = int(input("Please enter the third side of the triangle:")) # Enter the third edge and convert it to an integer s = 1 / 2 * (a + b + c) # Calculation s area = (s * (s - a) * (s - b) * (s - c)) # Call the sqrt function to calculate the area print("The area of this triangle is:", area) # Output triangle area
The results of the run are as follows.
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.