在Python中,文件操作是通过内置的open函数来实现的。
如果文件已经存在,open函数在默认模式下('r')会打开它进行读取,但如果使用写入模式('w')或追加模式('a'),它会覆盖或追加内容到文件中。如果文件不存在,这些写入模式会创建新文件。
文件操作的代码示例如下:
import os
import shutil
# 指定文件路径
file_path = 'D:/log/tech/python_file.txt'
# 获取目录路径(不包含文件名)
directory_path = os.path.dirname(file_path)
# 检查目录是否存在,如果不存在则创建它(包括所有必要的父目录)
if not os.path.exists(directory_path):
os.makedirs(directory_path)
# 使用'w'模式打开文件(如果文件不存在,则创建它)
# 在Python中,with语句被设计用来简化资源管理,确保诸如文件或网络连接等资源在使用完毕后能被正确地关闭或释放。
# 当使用with语句打开一个文件时,它会在代码块执行完毕后自动关闭文件,即便在代码块内部发生了异常。
# with语句创建了一个上下文管理器,它负责在代码块开始之前准备资源(在这里是打开文件),并在代码块执行完毕后释放资源(关闭文件)。
with open(file_path, 'w', encoding='utf-8') as file:
# 可以选择写入一些初始内容
file.write('This is a new file.\n')
print(f"The file {file_path} has been created.") # 输出:The file D:/log/tech/python_file.txt has been created.
with open(file_path, 'r', encoding='utf-8') as file:
print(f"read:{file.read()}") # 输出:read:This is a new file.
# 打开文件并写入内容(如果文件不存在,会自动创建)
# 此时打开方式为'w',则上面写入的内容This is a new file被覆盖
with open(file_path, 'w', encoding='utf-8') as file:
file.write('Hello, World!\t')
file.write('This is a new line.\n')
# 打开文件并追加内容(如果文件不存在,会自动创建)
with open(file_path, 'a', encoding='utf-8') as file:
file.write('Hello world!\t')
file.write('Appending a new line.\n')
# 打开文件并读取内容
# 在代码结尾无需手动关闭文件,因为with语句会在代码块执行完毕后自动关闭它
# open函数返回一个文件对象,这个对象在with语句中被临时赋值给变量file
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
print(f"readContent:\n{content}")
# 上面的代码输出:
"""
readContent:
Hello, World! This is a new line.
Hello world! Appending a new line.
"""
# 打开文件并逐行读取内容
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
print(f"line read:{line.strip()}") # 使用strip()去除每行末尾的换行符
# 上面的代码输出:
# line read:Hello, World! This is a new line.
# line read:Hello world! Appending a new line.
# 读取文件内容
with open(file_path, 'r', encoding='utf-8') as file:
# file.readlines()方法读取文件中的所有行,并将它们作为一个字符串列表存储在变量lines中。
# 每个字符串代表文件中的一行,包括行尾的换行符(如果有的话)。
lines = file.readlines()
print(f"readLines:{lines}")
# 上面的代码输出:
# readLines:['Hello, World!\tThis is a new line.\n', 'Hello world!\tAppending a new line.\n']
# 修改文件内容(例如,将所有行转换为大写)
# 使用列表推导式遍历lines列表中的每一行
modified_lines = [line.strip().upper() + '\n' for line in lines]
# 将修改后的内容追加回文件(使用'w'的话则是覆盖原文件)
with open(file_path, 'w', encoding='utf-8') as file:
file.writelines(modified_lines)
with open(file_path, 'r', encoding='utf-8') as file:
# readlines()读取文件的所有行,并返回一个包含各行的列表.readLine()读取文件的一行
# read(size=-1):读取整个文件内容(如果指定 size,则读取 size 个字符)。
newContent = file.readlines()
print(f"Upper readLines:{newContent}")
# 上面的代码输出:
# Upper readLines:['HELLO, WORLD!\tTHIS IS A NEW LINE.\n', 'HELLO WORLD!\tAPPENDING A NEW LINE.\n']
src_file = file_path
dst_file = 'D:/log/tech/file_copy.txt'
moved_file = 'D:/log/tech/file_move.txt'
# 复制文件
if os.path.exists(src_file):
# shutil是Python标准库中的一个高级文件操作模块,提供了许多便捷的文件和目录管理功能,例如复制、移动、删除和压缩文件。
shutil.copy(src_file, dst_file)
print(f"The file {src_file} has been copied to {dst_file}.")
else:
print(f"The source file {src_file} does not exist.")
# 重命名文件
if os.path.exists(dst_file):
shutil.move(dst_file, moved_file)
print(f"The file {dst_file} has been moved to {moved_file}.")
else:
print(f"The source file {dst_file} does not exist.")
# 获取文件大小
if os.path.exists(file_path):
file_size = os.path.getsize(file_path)
print(f"The size of the file {file_path} is {file_size} bytes.")
else:
print(f"The file {file_path} does not exist.")
# 删除文件
if os.path.exists(moved_file):
os.remove(moved_file)
print(f"The file {moved_file} has been deleted.")
else:
print(f"The file {moved_file} does not exist.")
# 判断文件是否存在
if os.path.exists(moved_file):
print(f"The file {moved_file} exists.")
else:
print(f"The file {moved_file} does not exist.")
在上面的代码中,引入了shutil模块,shutil模块提供了一系列对文件和文件集合进行高级操作的函数。
在使用shutil.copy时,请确保目标路径(dst_file)所在的目录存在。如果目标目录不存在,shutil.copy将引发一个FileNotFoundError异常。不过,shutil.copy会自动创建目标文件,但不会创建目标文件的父目录。
如果需要复制文件的权限、所有者、时间戳等元数据,请使用shutil.copy2函数。