【问题标题】:Python run script on several csv filesPython 在几个 csv 文件上运行脚本
【发布时间】:2021-10-25 16:13:45
【问题描述】:

我正在尝试在多个 .csv 文件上运行我的脚本并从每个文件中输出结果。我的一个sn-p代码如下-

import sys
import os
import logging
import subprocess
import argparse
import pandas as pd
import glob


files = glob.glob('/scratch/*/*.csv')

for file in files:
        df = pd.read_csv(file,delimiter = ',',skiprows=range(1,11))

#do some calculation on each file


#calculate the final value
metric = (max(max(dif_r1a),max(dif_r1c),max(dif_r1g),max(dif_r1t),max(dif_r2a),max(dif_r2c),max(dif_r2g),max(dif_r2t)))

#output the final value for each csv file
print(os.path.basename(file) + ' ' + str(metric))

我得到的输出仅适用于单个 csv 文件

file1.csv 0.25

如何迭代它以输出所有 csv 文件的值?

谢谢

【问题讨论】:

  • 你写的代码和上面贴的完全一样吗?您不是要缩进其余代码以在 for 循环中吗?

标签: python loops csv output


【解决方案1】:

根据上面代码中的显示,您可以为每个 .csv 文件创建一个数据框,但仅在执行 for 循环后计算最终值并打印。如果您想为每个数据帧执行此操作,则需要在 for 循环中:

import sys
import os
import logging
import subprocess
import argparse
import pandas as pd
import glob


files = glob.glob('/scratch/*/*.csv')

for file in files:
        df = pd.read_csv(file,delimiter = ',',skiprows=range(1,11))

#do some calculation on each file


#calculate the final value
metric = (max(max(dif_r1a),max(dif_r1c),max(dif_r1g),max(dif_r1t),max(dif_r2a),max(dif_r2c),max(dif_r2g),max(dif_r2t)))

#output the final value for each csv file
print(os.path.basename(file) + ' ' + str(metric))

这是您目前拥有的,但您希望将其更改为:

import sys
import os
import logging
import subprocess
import argparse
import pandas as pd
import glob


files = glob.glob('/scratch/*/*.csv')

for file in files:
    df = pd.read_csv(file,delimiter = ',',skiprows=range(1,11))

    #do some calculation on each file


    #calculate the final value
    metric = 
    (max(max(dif_r1a),max(dif_r1c),max(dif_r1g),max(dif_r1t), \
    max(dif_r2a),max(dif_r2c),max(dif_r2g),max(dif_r2t)))

    #output the final value for each csv file
    print(os.path.basename(file) + ' ' + str(metric))

但这也可能是由于评论的格式。

【讨论】:

    猜你喜欢
    • 2015-09-03
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 2020-02-13
    • 2014-01-07
    • 1970-01-01
    相关资源
    最近更新 更多