python将每个多行数据合并为一行并保存至另外的txt

数据处理真的头疼:我的数据是每个txt是点坐标信息,两列形式,要将每一张图片的点坐标信息变为一行,并保存至另外的txt

import os
path = r'D:\point_regression-master\point_regression-master\cdata\txt_file'  # 文本存放的路径
txt_list=os.listdir(path)
for i in txt_list:
    location=os.path.join(path,i)
    with open(location) as file:
        lines = file.readlines()  # 读取每一行
    a = ' '  # 空字符(中间不加空格)
    for line in lines:
        a += line.strip() # strip()是去掉每行末尾的换行符\n
    txt_filename = i[:-4] + ".txt"
    save_path="D:\\point_regression-master\\point_regression-master\\cdata\\txtline\\"+txt_filename
    with open(save_path,'w',encoding='utf-8') as f:
        f.write(a)

之前的想法太蠢,之间文本追加,每一个图像坐标换行追加至一张txt文件

import os
path = r'D:\point_regression-master\point_regression-master\cdata\txt_file_1'  # 文本存放的路径
txt_list=os.listdir(path)
txt_list.sort(key=lambda x: int(x.split('file_')[1].split('.txt')[0]))
for i in txt_list:
    location=os.path.join(path,i)
    with open(location) as file:
        lines = file.readlines()  # 读取每一行
    a = ' '  # 空字符(中间不加空格)
    for line in lines:
        a += line.strip() # strip()是去掉每行末尾的换行符\n
        a=a+' '
    # txt_filename = i[:-4] + ".txt"
    # save_path="D:\\point_regression-master\\point_regression-master\\cdata\\txtline\\"+txt_filename
    # with open(save_path,'w',encoding='utf-8') as f:
    #     f.write(a)
    f='lucky.txt'
    with open(f,'a',encoding='utf-8') as file:
        file.write(a+" "+"\n")

你可能感兴趣的:(学习自存,python,开发语言)