21-Python-文件操作
在Python中,文件操作是非常重要的一部分,它允许我们读取、写入和修改文件。下面将详细讲解Python文件操作的各个方面,并给出相应的示例。
1-打开文件
在Python中,使用`open()`函数来打开一个文件。`open()`函数接受两个主要参数:文件名和打开模式。
1-1-打开模式
`'r'`:只读模式,默认值。如果文件不存在,会抛出`FileNotFoundError`异常。
`'w'`:写入模式。如果文件已存在,会清空文件内容;如果文件不存在,则创建新文件。
`'a'`:追加模式。如果文件已存在,会在文件末尾追加内容;如果文件不存在,则创建新文件。
`'x'`:创建模式。如果文件已存在,会抛出`FileExistsError`异常;如果文件不存在,则创建新文件。
`'b'`:二进制模式,可以与其他模式结合使用,如`'rb'`(二进制只读)、`'wb'`(二进制写入)等。
`'t'`:文本模式,默认值,可以与其他模式结合使用,如`'rt'`(文本只读)。
1-2-示例代码
# 以只式开文件
file = open('test.txt', 'r')
print(file)
file.close()
输出结果
2-读取文件
2-1-读取文件方法
打开文件后,可以使用以下方法读取文件内容:
`read()`:读取整个文件内容。
`readline()`:读取文件的一行内容。
`readlines()`:读取文件的所有行,并返回一个列表,每个元素是文件的一行。
2-2-示例代码
# 以只读模式打开文件
file = open('test.txt', 'r')
# 使用read()方法读取整个文件内容
content = file.read()
print("使用read()方法读取的内容:")
print(content)
# 重新打开文件,因为之前的文件指针已经到了文件末尾
file = open('test.txt', 'r')
# 使用readline()方法读取一行内容
line = file.readline()
print("\n使用readline()方法读取的第一行内容:")
print(line)
# 重新打开文件
file = open('test.txt', 'r')
# 使用readlines()方法读取所有行
lines = file.readlines()
print("\n使用readlines()方法读取的所有行内容:")
for line in lines:
print(line)
# 关闭文件
file.close()
3- 写入文件
3-1-作用
使用`write()`方法可以向文件中写入内容。
3-2-示例代码
# 以写入模式打开文件
file = open('test_write.txt', 'w')
# 写入内容
file.write("Hello, World!\n")
file.write("This is a test file.\n")
# 关闭文件
file.close()
# 以追加模式打开文件
file = open('test_write.txt', 'a')
# 追加内容
file.write("This is an appended line.\n")
# 关闭文件
file.close()
#读取
file = open('test_write.txt', 'r')
print('读取写入的内容......')
lines = file.readlines()
for line in lines:
print(line)
# 关闭文件
file.close()
4-使用`with`语句
4-1-作用
`with`语句可以自动管理文件的打开和关闭,避免忘记关闭文件而导致资源泄漏。
4-2-示例代码
# 使用with语句写入文件
with open('test_with.txt', 'w') as file:
file.write("This is a file created using with statement.\n")
# 使用with语句读取文件
with open('test_with.txt', 'r') as file:
content = file.read()
print(content)
输出结果
5-文件指针操作
5-1-作用
可以使用`seek()`方法移动文件指针的位置,使用`tell()`方法获取文件指针的当前位置。
5-2-示例代码
with open('test.txt', 'r') as file:
# 获取文件指针的初始位置
position = file.tell()
print(f"初始位置:{position}")
# 读取一行内容
line = file.readline()
print(line)
# 获取文件指针的当前位置
position = file.tell()
print(f"当前位置:{position}")
# 移动文件指针到文件开头
file.seek(0)
# 获取文件指针的新位置
position = file.tell()
print(f"移动后的位置:position}")
以上就是Python文件操作的基本内容,通过这些操作,你可以方便地对文件进行读取、写入和修改。
6-拷贝文件
6-1-使用 `shutil` 模块的 `copy2` 函数
`shutil.copy2` 函数在复制文件时会尽量保留原文件的元数据(如文件的创建时间、修改时间等)。
shutil 模块提供了一系列用于高级文件操作的函数,尤其是文件和目录的复制、移动、删除等操作
import shutil
def copy_file(source, destination):
try:
shutil.copy2(source, destination)
print(f"文件 {source} 已成功复制到 {destination}")
except FileNotFoundError:
print(f"错误:源文件 {source} 未找到。")
except PermissionError:
print("错误:没有足够的权限进行文件复制操作。")
except Exception as e:
print(f"发生未知错误:{e}")
# 示例调用
if __name__ == "__main__":
source_file = 'source.txt'
destination_file = 'dest.txt'
copy_file(source_file, destination_file)
6-2-手动逐块读取和写入文件
这种方法通过手动打开源文件和目标文件,逐块读取源文件内容并写入目标文件,适合处理大文件。
def copy_file_manually(source, destination):
try:
with open(source, 'rb') as src_file:
with open(destination, 'wb') as dest_file:
while True:
chunk = src_file.read(4096)
if not chunk:
break
dest_file.write(chunk)
print(f"文件 {source} 已成功复制到 {destination}")
except FileNotFoundError:
print(f"错误:源文件 {source} 未找到。")
except PermissionError:
print("错误:没有足够的权限进行文件复制操作。")
except Exception as e:
print(f"发生未知错误:{e}")
# 示例调用
if __name__ == "__main__":
source_file = 'source.txt'
destination_file = 'destination.txt'
copy_file_manually(source_file, destination_file)
7-os模块
7-1-作用
`os` 模块提供了使用操作系统相关功能的函数,如文件和目录操作、进程管理、环境变量访问等。
7-2-获取当前工作目录
import os
# 获取当前工作目录
current_dir = os.getcwd()
print(f"当前工作目录: {current_dir}")
7-3-创建目录
import os
# 获取当前目录下的所有文件和子目录
files_and_dirs = os.listdir()
print("当前目录下的文件和子目录:")
for item in files_and_dirs:
print(item)
7-4-列出目录中的文件和子目录
import os # 获取当前目录下的所有文件和子目录 files_and_dirs = os.listdir() print("当前目录下的文件和子目录:") for item in files_and_dirs: print(item)
7-5-删除文件
import os
# 定义要删除的文件名
file_to_delete = "test.txt"
# 如果文件存在,则删除它
if os.path.exists(file_to_delete):
os.remove(file_to_delete)
print(f"文件 {file_to_delete} 已删除")
else:
print(f"文件 {file_to_delete} 不存在")
8-练习题
8-1-题目
创建一个 Python 脚本,用于将指定源目录下的所有文件备份到目标目录。若目标目录不存在,则自动创建。同时,备份时会保留文件的原始目录结构。
8-2-代码
import os
import shutil
def backup_files(source_dir, target_dir):
# 检查目标目录是否存在,若不存在则创建
if not os.path.exists(target_dir):
os.makedirs(target_dir)
# 遍历源目录下的所有文件和文件夹
for root, dirs, files in os.walk(source_dir):
# 计算当前子目录在目标目录中的路径
relative_path = os.path.relpath(root, source_dir)
target_sub_dir = os.path.join(target_dir, relative_path)
# 若目标子目录不存在,则创建
if not os.path.exists(target_sub_dir):
os.makedirs(target_sub_dir)
# 遍历当前子目录下的所有文件
for file in files:
source_file_path = os.path.join(root, file)
target_file_path = os.path.join(target_sub_dir, file)
try:
# 复制文件
shutil.copy2(source_file_path, target_file_path)
print(f"已备份文件: {source_file_path} -> {target_file_path}")
except Exception as e:
print(f"备份文件 {source_file_path} 时出错: {e}")
if __name__ == "__main__":
source_directory = "source"
target_directory = "backup"
backup_files(source_directory, target_directory)