python 批量处理TXT文档内容

python 批量处理txt文件内容
使用python 完成txt文档内容转换

img

img

转换前
文件夹中有批量的txt文档
内容为
第一行 为总坐标数量
第二、三、四、五行 为坐标信息
目标
转换后
去除第一行总坐标数量、
只保留坐标信息、且浮点转换为三位数百位数整数

*另外将txt文档全部转换为.pts文件类型

运行效果如图:

img

import os


# 遍历文件夹
def walkFile(file):
    for root, dirs, files in os.walk(file):
        # 遍历文件
        for f in files:
            # 非txt跳过文件
            if (not f.endswith('.txt') or f.endswith("_transfer.txt")):
                continue
            new_file = os.path.join(root, f.replace('.txt', '_transfer.pts'))
            print(os.path.join(root, f))
            with open(os.path.join(root, f), "r") as f:  # 打开文件
                strs = str(f.read())  # 读取文件
                print(strs)
                strs = strs.split('\n')

                replace_str = ''
                for i, coords in enumerate(strs):
                    if (i == 0):  # 跳过第一行数字
                        continue
                    coords = [str(round(float(i), 3)) for i in coords.replace("\n", '').split(" ")]
                    format_str = ' '.join(coords)
                    replace_str = replace_str + format_str + '\n'

                print('after transfer: ')
                print(new_file)
                print(replace_str)
                with open(new_file, "w") as f2:  # 写入新文件
                    f2.write(replace_str)

walkFile("txts/")

如有帮助,请点个采纳哦~

图二中浮点转换为保留3位小数看懂了,图一中浮点数转百位数整数原则是什么呢?