要复制一个文件并在开头添加一行,可以使用以下代码示例:
def copy_file_with_header(source_file, destination_file, header_line):
# 打开源文件以读取内容
with open(source_file, 'r') as source:
# 读取源文件内容
content = source.read()
# 将头行添加到内容开头
content_with_header = header_line + '\n' + content
# 打开目标文件以写入内容
with open(destination_file, 'w') as destination:
# 将内容写入目标文件
destination.write(content_with_header)
# 定义源文件路径、目标文件路径和要添加的头行
source_file = 'source_file.txt'
destination_file = 'destination_file.txt'
header_line = 'This is the header line.'
# 调用函数来复制文件并添加头行
copy_file_with_header(source_file, destination_file, header_line)
以上代码定义了一个名为copy_file_with_header
的函数,它接受源文件路径、目标文件路径和头行作为参数。函数首先打开源文件,并读取其内容。然后,将头行添加到内容的开头,并将其保存到一个新的变量content_with_header
中。最后,函数打开目标文件,并将带有头行的内容写入该文件。
你可以将源文件路径、目标文件路径和要添加的头行替换为你自己的实际值,并调用copy_file_with_header
函数来复制文件并添加头行。