python 批量处理txt文件内容

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

img

img


转换前
文件夹中有批量的txt文档
内容为
第一行 为总坐标数量
第二、三、四、五行 为坐标信息

目标
转换后
去除总坐标数量、
只保留坐标信息、且为三位数整数

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

在写入行数据时根据需要进行调整即可。参考示例:

a=['0.2345','0.2351','3.2212']
y=[int(float(x)) for x in a]#浮点数字符串转整数
print(y)
z=[int(float(x.split('.')[-1][:3])) for x in a]#只对小数点后前三位取整
print(z)



```python
def trans(root_dir):
    for f in os.listdir(root_dir):
        if f.endswith(".txt"):
            f_name = os.path.splitext(f)[0]
            f_path = os.path.join(root_dir, f)
            pts_f = os.path.join(root_dir, f"{f_name}.pts")
            print(f"Trans {f} to {os.path.basename(pts_f)}")
            with open(f_path, "r") as rf, open(pts_f, "w")as wf:
                for idx, line in enumerate(rf):
                    if idx > 0:
                        new_line = " ".join(["{:.3f}".format(float(x)) for x in line.strip().split()])
                        wf.write(new_line + "\n")
    print("Done!")


if __name__ == '__main__':
    # trans("txt所在的文件夹")
    trans(r"C:\Users\terra_cai\Desktop\test")

```

可以用正则表达式来搞,不是很麻烦



```python
import os
from PIL import Image


class MyImage:
    def __init__(self, img_path):
        self.img_path = img_path
        img = Image.open(self.img_path)
        self.width = int(img.size.width)
        self.height = int(img.size.height)
        self.ori_points = []
        self.pts = []
        self.pts_file = self.img_path.replace(".jpg", ".pts")
        self.txt_file = self.img_path.replace(".jpg", ".txt")
        if os.path.exists(self.txt_file):
            self.__get_pts()
            self.__calculate_pts()
            self.__create_pts()
        else:
            print(f"Not exist txt file,Ignore {self.img_path}!")

    def __calculate_pts(self):
        for x, y in self.ori_points:
            self.pts.append((int(x * self.width), int(y * self.height)))

    def __get_pts(self):
        with open(self.txt_file, "r") as rf:
            for idx, line in enumerate(rf):
                if idx > 0:
                    x, y = (float(x) for x in line.strip().split())
                    self.ori_points.append((x, y))

    def __create_pts(self):
        with open(self.pts_file, "w") as wf:
            for x, y in self.pts:
                wf.write(f"{x} {y}\n")


if __name__ == '__main__':
    # trans("txt所在的文件夹")
    root_dir = r"C:\Users\terra_cai\Desktop\test"
    for file in os.listdir(root_dir):
        if file.endswith(".jpg"):
            img = MyImage(os.path.join(root_dir, file))


```