Home >Backend Development >Python Tutorial >How to read files and output them in python
Python reads files and outputs
How to read files and output?
In Python, you can use the open()
function to open a file, and then use the read()
method to read the file contents.
Detailed steps:
Open the file:
<code class="python">file = open("my_file.txt", "r")</code>
Among them:
"my_file.txt"
is the path of the file to be opened. "r"
means opening the file in read-only mode. Read file content:
<code class="python">file_content = file.read()</code>
This line of code reads the entire file content into the file_content
variable.
Output file content:
<code class="python">print(file_content)</code>
This line of code will print the file content in the console.
Close the file:
<code class="python">file.close()</code>
After reading the file, be sure to close the file to release resources.
Full example:
<code class="python">with open("my_file.txt", "r") as file: file_content = file.read() print(file_content)</code>
Use the with
statement to simplify your code by automatically closing the file at the end of the block.
The above is the detailed content of How to read files and output them in python. For more information, please follow other related articles on the PHP Chinese website!