一文掌握Python中的文件操作
Python为文件处理提供了一组通用的工具和函数,使得对文件执行各种操作相对简单。这些操作包括打开文件、阅读其内容、写入新数据、追加到现有文件等。
文件可以包含广泛的信息,从纯文本文档到图像、数据库、电子表格等。Python的文件处理功能旨在适应这些不同类型的数据,使其成为数据分析,数据操作和自动化等任务的强大工具。
打开和关闭文件
可以使用 open() 功能打开文件。它有两个参数:文件路径和模式。一旦你完成了一个文件,使用 close() 关闭它是很重要的。
模式:
- 'r' :读取模式。允许您读取文件的内容。
- 'w' :写入模式。允许您将数据写入文件。它将覆盖现有内容。
- 'a' :追加模式。允许您将数据添加到现有文件的末尾。
- 'b' :二进制模式。用于处理非文本文件,如图像或可执行文件。
- 'x' :独家创作。创建一个新文件,但如果该文件已存在,则会引发错误。
# Opening a file for reading
file = open('example.txt', 'r')
# Opening a file for writing (creates a new file if it doesn't exist, and truncates if it does)
file = open('example.txt', 'w')
# Opening a file for appending (appends to the end of an existing file)
file = open('example.txt', 'a')
# Opening a file in binary mode
file = open('example.txt', 'rb')
# Closing a file
file.close()
读取文件
可以使用 read() 方法从文件中读取。它读取文件的全部内容,或者可以指定要读取的字节数。
file = open('example.txt', 'r')
content = file.read() # Reads the entire file
line = file.readline() # Reads a single line
lines = file.readlines() # Reads all lines and returns a list
print(content)
file.close()
写入文件
可以使用 write() 方法写入文件。这将用新内容替换现有内容。
file = open('example.txt', 'w')
file.write('Hello, World!')
file.close()
删除文件
如果想在不添加内容的情况下将内容添加到现有文件中,则可以在append模式下打开该文件并使用 write() 方法。
file = open('example.txt', 'a')
file.write('\nThis is an appended line.')
file.close()
使用二进制文件
二进制文件处理非文本文件,如图像,音频等。使用“rb”模式进行阅读,使用“rb”模式进行写入。
# Reading a binary file
with open('binary_file.jpg', 'rb') as file:
content = file.read()
# Writing to a binary file
with open('new_binary_file.jpg', 'wb') as file:
file.write(content)
使用with语句
with 语句会在您完成操作后自动关闭文件。
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# File is automatically closed here
文件位置
每当读或写一个文件,"光标"前进。可以使用 seek() 方法更改位置。
with open('example.txt', 'r') as file:
content = file.read(10) # Reads the first 10 characters
file.seek(0) # Move cursor back to the beginning
content = file.read(10) # Reads the next 10 characters
使用目录
Python的 os 模块提供了与文件系统交互的函数。
import os
# Create a directory
os.mkdir('my_directory')
# List files in a directory
files = os.listdir('my_directory')
print(files)
# Remove a file
os.remove('my_file.txt')
# Remove an empty directory
os.rmdir('my_directory')
使用os模块进行文件操作
os 模块提供各种文件操作。
import os
# Rename a file
os.rename('old_name.txt', 'new_name.txt')
# Get the current working directory
cwd = os.getcwd()
# Change the working directory
os.chdir('/path/to/directory')
# Check if a file exists
os.path.exists('file.txt')