利用Python批量处理多个txt文本

(1)提取特定波段的行数据 

import glob
import pandas as pd

def extract_lines_from_txt_files(file_pattern, target_wavelength):
    # 获取符合文件模式的txt文件路径列表
    file_paths = glob.glob(file_pattern)

    results = []
    for file_path in file_paths:
        with open(file_path, 'r') as file:
            lines = file.readlines()

            # 提取包含目标波长的行
            target_lines = []
            for line in lines:
                if target_wavelength in line:
                    target_lines.append(line.strip())

            # 添加文件路径和提取结果到列表
            results.append({'File': file_path, 'Lines': target_lines})

    return results

# 设置文件模式和目标波长
file_pattern = 'D:\\Users\\DELL\\Desktop\\test\\VIS=5\\*.txt'    # 根据实际的列名或波长进行设置
target_wavelength = '21321'  # 设置特定波长的字符串

# 调用函数提取行数
output = extract_lines_from_txt_files(file_pattern, target_wavelength)

# 创建DataFrame对象
df = pd.DataFrame(output)

# 保存结果到Excel文件
output_file = 'D:\\Users\\DELL\\Desktop\\PDF\\result.xlsx'  # 设置输出文件路径和名称
df.to_excel(output_file, index=False)

print(f"提取结果已保存到 {output_file}")

(2)批量替换文本中的某个特定数值

# -*- coding: utf-8 -*-
"""
Created on Mon Nov 21 2022
@author: MMG
"""
# coding=utf-8

import os

path = "E:\\Program Files\\Nimbostratus cloud_100"
# new_path = "E:\\Program Files\\Mod5.2.2\\rural=5_view=136\\1"

def listfiles(dirpath):
    filelist = []
    for root, dirs, files in os.walk(dirpath):
        for fileObj in files:
            filelist.append(os.path.join(root, fileObj))
    return filelist
def main():
    filelist = listfiles(path)
    for fileobj in filelist:
        f = open(fileobj, 'r+')
        lines = f.readlines()
        f.seek(0)
        f.truncate()
        for line in lines:
            f.write(line. Replace('45.50000'#原文本,'5.000000'#改过后的数值))
        f.close()


if __name__ == main():
    main()

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