Python循环使用查找表中的三个变量

bkhjykvo  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(137)

请原谅我,因为我还在学习Python。我试图想出一种方法来构建一个循环,使用来自查找表的多行三个变量。
查找表包含一个编号索引和三个拆分为列的变量。大约有290行,每一行代表一个我的目标循环。
我的python脚本正在工作,但我必须复制/粘贴290个项目的代码。有没有一种方法可以构建一个从查找表中获取三个变量的循环?
查找表示例:
x1c 0d1x的数据
Python脚本:

import pandas as pd
import os, shutil
import numpy as np

# Import Lookup Table
# Can this table be used as a lookup for loop variables myfile, pname, and ename?
DF_LU = 'E:/Python Projects/ParmAudit/LUParm.csv'

# Source and Export Directories
sourcedir = 'E:/Python Projects/ParmAudit/Dump/'
exportdir = 'E:/Python Projects/ParmAudit/Export/'

# cbrs_alarm

# These variables change based on each row from the lookup table 
myfile = 'N_1.txt'
pname = 'cbrs_alarm_threshold'
ename = 'cbrs_alarm_threshold.csv'

# Remove 1st row for clean csv file
with open(os.path.join(sourcedir, myfile)) as f:
    lines = list(f)

lines.pop(0)  # delete 1st row

# Write lines back into file
with open(os.path.join(sourcedir, myfile), "w") as f:
    for line in lines:
        f.write(line)

#Create dataframe
DF = pd.read_csv(os.path.join(sourcedir, myfile))
#Add column to dataframe
DF['STA_Parm'] = pname
#Set new column as the first column
first_column = DF.pop('STA_Parm')
DF.insert(0, 'STA_Parm', first_column)

#Export DF to CSV
DF.to_csv(os.path.join(exportdir, ename), index=False)

# acdc_profiles

myfile = 'N_3.txt'
pname = 'acdc_profiles'
ename = 'acdc_profiles.csv'

with open(os.path.join(sourcedir, myfile)) as f:
    lines = list(f)

lines.pop(0)

# Write lines back into file
with open(os.path.join(sourcedir, myfile), "w") as f:
    for line in lines:
        f.write(line)
        
DF = pd.read_csv(os.path.join(sourcedir, myfile))
DF['STA_Parm'] = pname
first_column = DF.pop('STA_Parm')
DF.insert(0, 'STA_Parm', first_column)
#display(DF)
DF.to_csv(os.path.join(exportdir, ename), index=False)

字符串

mu0hgdu0

mu0hgdu01#

使用csv模块循环浏览CSV文件,分配文件每一列的变量。

with open(DF_LU) AS lu_file:
    lu_csv = csv.reader(lu_file)
    for LU_index, myfile, pname, ename in lu_csv:
        # your code here

字符串

相关问题