首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

python将文件前缀和特定内容写入另一个文件的列表

Python可以通过以下代码将文件前缀和特定内容写入另一个文件的列表:

代码语言:txt
复制
import os

def write_file_with_prefix(file_path, prefix, content):
    # 获取文件名和扩展名
    file_name, file_ext = os.path.splitext(file_path)
    
    # 构建新文件名
    new_file_name = prefix + file_name + file_ext
    
    # 写入文件
    with open(new_file_name, 'w') as new_file:
        new_file.write(content)

# 示例用法
file_path = 'example.txt'
prefix = 'new_'
content = 'This is the new content.'

write_file_with_prefix(file_path, prefix, content)

上述代码中,write_file_with_prefix函数接受三个参数:file_path表示原始文件的路径,prefix表示要添加的前缀,content表示要写入新文件的内容。

首先,通过os.path.splitext函数获取原始文件的文件名和扩展名。然后,使用prefix和原始文件名构建新的文件名。最后,使用open函数以写入模式打开新文件,并使用write方法写入指定的内容。

这样,就可以将原始文件的前缀和特定内容写入新的文件中。

请注意,上述代码仅为示例,实际应用中可能需要添加错误处理、路径验证等额外的逻辑。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券