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-tempfile模块
8-1-作用
`tempfile` 是 Python 标准库中的一个模块,用于创建临时文件和临时目录。
它非常适合在需要临时存储数据的场景中使用,例如缓存、中间计算结果等。
`tempfile` 模块会自动处理临时文件的创建和清理,避免手动管理文件的麻烦。
8-2-创建临时文件
使用 `tempfile.TemporaryFile` 创建一个临时文件。该文件在关闭后会自动删除。
代码
import tempfile
# 创建一个临时文件
with tempfile.TemporaryFile(mode='w+') as temp:
temp.write("Hello, World!")
temp.seek(0) # 将文件指针移回开头
print(temp.read()) # 输出内容
# 文件在 with 块结束后自动删除
特点
文件默认存储在内存中(如果可能),否则存放在磁盘上。关闭文件后,文件会被自动删除。
8-2-创建命名临时文件
使用 `
tempfile.NamedTemporaryFile` 创建一个具有名称的临时文件。可以通过 `.name` 属性访问文件路径。
代码
import tempfile
import os
# 创建一个命名临时文件
with tempfile.NamedTemporaryFile(delete=False) as temp:
temp.write(b"Hello, Named Temporary File!")
print("文件名:", temp.name)
print("文件内容:", open(temp.name, 'r').read())
os.unlink(temp.name) # 手动删除文件(因为 delete=False)
特点
- 可以通过 `.name` 获取文件路径。
- 如果 `delete=True`(默认值),文件会在关闭时自动删除;如果设置为 `False`,则需要手动删除。
8-3-创建临时目录
使用 `
tempfile.TemporaryDirectory` 创建一个临时目录。目录在关闭后会自动删除。
代码
import tempfile
import os
# 创建一个临时目录
with tempfile.TemporaryDirectory() as temp_dir:
print("临时目录:", temp_dir)
# 在临时目录中创建一个文件
file_path = os.path.join(temp_dir, "example.txt")
with open(file_path, 'w') as f:
f.write("This is a test file.")
print("文件内容:", open(file_path, 'r').read())
# 目录在 with 块结束后自动删除
特点
- 目录及其内容会在 `with` 块结束后自动删除。
- 非常适合需要多个临时文件的场景。
8-4-手动生成临时文件或目录的名称
使用 `tempfile.mkstemp` 或 `tempfile.mkdtemp` 手动生成临时文件或目录的名称。
代码
import tempfile
import os
# 创建一个临时文件(返回文件描述符和文件路径)
fd, temp_file_path = tempfile.mkstemp()
print("临时文件路径:", temp_file_path)
with os.fdopen(fd, 'w') as temp: # 写入数据到临时文件
temp.write("Hello, mkstemp!")
os.unlink(temp_file_path) # 手动删除文件
temp_dir_path = tempfile.mkdtemp()# 创建一个临时目录
print("临时目录路径:", temp_dir_path)
os.rmdir(temp_dir_path) # 手动删除目录
特点
`mkstemp` 和 `mkdtemp` 不会自动清理资源,需要手动删除。
更适合需要自定义文件或目录管理的场景。
8-5-获取系统临时目录
使用 `tempfile.gettempdir()` 获取系统的临时目录路径。
import tempfile
print("系统临时目录:", tempfile.gettempdir())
```
**输出示例:**
```
系统临时目录: /tmp # Linux/macOS
系统临时目录: C:\Users\<用户名>\AppData\Local\Temp # Windows
8-6-高级选项
`tempfile` 提供了一些高级选项,例如指定文件前缀、后缀或目录。
import tempfile
# 创建带有特定前缀和后缀的临时文件
with tempfile.NamedTemporaryFile(prefix="my_prefix_", suffix=".txt", dir="/tmp") as temp:
print("临时文件路径:", temp.name)
9-练习题
9-1-题目
创建一个 Python 脚本,用于将指定源目录下的所有文件备份到目标目录。若目标目录不存在,则自动创建。同时,备份时会保留文件的原始目录结构。
9-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)