gpt4 book ai didi

python - 将一个文件的代码应用于多个文件python(新手问题)

转载 作者:行者123 更新时间:2023-12-04 09:10:12 26 4
gpt4 key购买 nike

我编写了以下代码,该代码从 csv 文件中获取一列,然后将其转换为整数并将它们全部相加。我只为一个文件完成了此操作,并且我有大约 80 个文件可以应用相同的代码。

import csv
from collections import defaultdict
columns = defaultdict(list)
with open('Team11BoM.csv') as f:
reader = csv.DictReader(f)
for row in reader:
for (k,v) in row.items():
if k not in columns:
columns[k] = list()
columns[k].append(v)

import pandas as pd
df = pd.read_csv("Team11BoM.csv")

b = list(df['Reported Price'])
a = list(df['Actual Price'])

for i in range(0, len(a)):
a[i] = int(float(a[i]))

v = sum(a)
print("the total actual cost(s) for team 11 is:", v)

for i in range(0, len(b)):
b[i] = int(float(b[i]))

h = sum(b)
print("the total reported price for team 11 is:", h)
它打印出以下内容:
the total actual cost(s) for team 11 is: 945
the total reported price for team 11 is: 707
我希望它打印出来:
the total actual cost(s) for *filename* is: *Total cost of that team*
the total reported price for *filename* is: *Total reported price of that team*
有没有简单的方法可以做到这一点?
谢谢,
伊尔凡·S。

最佳答案

import os
import csv
import pandas as pd
from collections import defaultdict

files_dir = 'csv'

csv_files = os.listdir(files_dir)
print(csv_files)

def convert_to_int(file_name):
file_name = f'{files_dir}/{file_name}'
columns = defaultdict(list)
with open(file_name) as f:
reader = csv.DictReader(f)
for row in reader:
for (k,v) in row.items():
if k not in columns:
columns[k] = list()
columns[k].append(v)

df = pd.read_csv(file_name)

b = list(df['Reported Price'])
a = list(df['Actual Price'])

for i in range(0, len(a)):
a[i] = int(float(a[i]))

v = sum(a)
print("the total actual cost(s) for team 11 is:", v)

for i in range(0, len(b)):
b[i] = int(float(b[i]))

h = sum(b)
print("the total reported price for team 11 is:", h)

for file in csv_files:
convert_to_int(file)

关于python - 将一个文件的代码应用于多个文件python(新手问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63364468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com