|  | 
 
 发表于 2023-9-28 12:22:33
|
显示全部楼层 
| 您可以使用Python的os模块中的rename()函数来实现将新文件的内容保存到旧文件中,并且删除新文件的操作。代码如下: 
 
 复制代码import os
import glob
# 获取当前文件夹下的所有txt文件
txt_files = glob.glob("*.TXT")
for file in txt_files:
    # 新文件的文件名,添加"_updated"后缀
    new_file = file.split(".")[0] + "_updated." + file.split(".")[1]
    with open(file, 'r') as f:
        with open(new_file, 'w') as new_f:
            # 逐行读取并处理文档内容
            for line in f:
                if len(line) < 14:
                    # 如果行长度小于14个字符,不进行处理
                    new_f.write(line)
                else:
                    # 在指定位置插入空格
                    new_line = line[:4] + " " + line[4:6] + " " + line[6:8] + " " + line[8:10] + " " + line[10:12] + " " + line[12:14] + "  " + line[14:]
                    new_f.write(new_line)
                    
    # 将新文件的内容保存到旧文件中,并删除新文件
    os.remove(file)
    os.rename(new_file, file)
 在代码中,我们使用os模块中的remove()函数来删除旧文件,使用rename()函数来将新文件的内容保存到旧文件中,并删除新文件。
 | 
 |