Welcome to the Python file writing tutorial! In this section, we will explore how to work with files in Python. Whether you are new to Python or looking to expand your knowledge, this guide will help you understand the basics of file handling in Python.
创建文件
To create a file in Python, you can use the open()
function with the 'w'
mode. This mode stands for write, and it will create a new file or overwrite an existing one.
with open('example.txt', 'w') as file:
file.write('Hello, World!')
The above code will create a file named example.txt
and write "Hello, World!" to it.
读取文件
To read the contents of a file, you can use the open()
function with the 'r'
mode.
with open('example.txt', 'r') as file:
content = file.read()
print(content)
This code will open the example.txt
file and print its contents.
写入和读取文件
You can also write and read from the same file by opening it in append mode ('a'
) or read mode ('r+'
).
with open('example.txt', 'r+') as file:
file.write('\nAdding a new line.')
file.seek(0)
content = file.read()
print(content)
This code will add a new line to the example.txt
file and then read and print its contents.
图片插入
Here is an image of a Python cat: