循环创建具有特定文件名和内容的输出文件,该文件名和行内容相同

2024-06-26 00:30:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有n行的文件。我正在读取文件并将其分配给数据帧df。其中一个列名是curr_state。基于curr_state,我想为每个特定的curr_state创建不同的输出文件。输出文件必须遵循特定的名称约定。我用下面的代码单独完成了这项工作:

#curr_state:  curr.state
#to extract rows that contain current state "curr.state"
CurrStateName= (df.loc[df['curr_state'] == 'curr.state'])

#naming convention
OutputCurrStateName = "abc_" +str(Client) + "_" + str(Channel) + "_" + "CurrStateName" + "_" + str(filedate) + ".csv"
#output file to a csv file
CurrStateName.to_csv(OutputCurrStateName, sep=',', encoding='utf-8', index=False)

但是,我希望读取另一个csv文件,其中包含curr_state列表和对应于该curr_stateCurrStateName,并使用循环中的命名约定创建输出文件。你知道吗

包含当前状态的文件

curr_state.                 CurrStateName
hello.attempt             HelloAttempt
Goodbye.attempt      GoodbyeAttempt

我该怎么做?你知道吗


Tags: 文件csvto数据代码名称dfextract
1条回答
网友
1楼 · 发布于 2024-06-26 00:30:36

不建议使用动态命名的变量。它们很难跟踪,名称空间混乱,导致错误。相反,您可以将字典理解与GroupBy结合使用。你知道吗

例如,使用f字符串(Python 3.6+),并假设指定了字符串ClientChannelfiledate

d = {f'abc_{Client}_{Channel}_{state}_{filedate}': df_state \
     for state, df_state in df.groupby('curr_state')}

然后可以通过迭代数据帧字典输出CSV文件:

for k, v in d.items():
    v.to_csv(f'{k}.csv', sep=',', encoding='utf-8', index=False)

相关问题 更多 >