【问题标题】:Applying code for one file to multiple files python (Newbie Question)将一个文件的代码应用于多个文件python(新手问题)
【发布时间】:2020-12-01 11:46:35
【问题描述】:

我编写了以下代码,它从 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.

【问题讨论】:

  • 我为您的问题添加了答案。

标签: python python-3.x pandas csv file


【解决方案1】:
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)

【讨论】:

  • 对不起,迟到的问题,但我用文件名替换了 FOLDER_PATH,但它也给了我一个TypeError: listdir: path should be string, bytes, os.PathLike, integer or None, not module,我在代码中放了不带引号的文件名,还有更多我需要更改/添加?谢谢!
  • 不,你应该只配置文件夹路径,控制台在哪一行显示错误?
  • 完全错误是:Traceback (most recent call last): File "location of file", line 6, in <module> csv_files = os.listdir(csv) TypeError: listdir: path should be string, bytes, os.PathLike, integer or None, not module 我把文件名放到代码中像这样csv_files = os.listdir(csv)
  • os.listdir() 将文件夹名称作为字符串,因此如果您的文件夹名称为 csv,您应该像 os.listdir('csv') 那样进行操作。
  • 即使在文件夹 csv (csv_files = os.listdir('csv')) 周围加上引号,它也会给出两个错误:Traceback (most recent call last): File "file location", line 37, in <module> convert_to_int(file) File "file location", line 11, in convert_to_int with open(file_name) as f: FileNotFoundError: [Errno 2] No such file or directory: 'Team41BoM.csv'
【解决方案2】:

首先,您应该定义一个可重复使用的函数以避免代码重复。

import csv
from collections import defaultdict

def process_file(file_name):
    columns = defaultdict(list)
    with open(file_namename) 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(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(f"the total actual cost(s) for {file_name} 11 is:", v)

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

    h = sum(b)
    print(f"the total reported price for {file_name} 11 is:", h)

其次,调用这个函数并遍历文件列表:

# assuming all of this files are in the current directory

list_of_files = [f for f in os.listdir('.') if os.path.isfile(f)]
for file_name in list_of_files:
    process_file(file_name)

【讨论】:

  • 对于文件列表,我应该把所有的 csvs 放到一个文件夹中吗?
  • @IrfanS,假设所有文件都在同一个目录中,您可以使用files = [f for f in os.listdir('.') if os.path.isfile(f)] 来获取要迭代的文件列表。
【解决方案3】:

如何将 csvs 放在一个目录中并像这样执行循环:

import pandas as pd
def summer(f):
    name = f.split('.')[0]
    df = pd.read_csv(f)

    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(f"the total actual cost(s) for {name} is:", v)

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

    h = sum(b)
    print("the total reported price for {name} is:", h)

path = 'path/to/csv-files/directory/'

import os
for fil in os.listdir(path):
    summer(fil)

【讨论】:

  • 我正在使用 iCloud Drive,当我输入路径时显示“FileNotFoundError: [Errno 2] No such file or directory: 'iCloud Drive/desktop/IACCproject1'”这是 iCloud 驱动器的问题还是还有什么?
  • iCloud 驱动器位于:/home/yourusername/Library/Mobile Documents/com~apple~CloudDocs/
【解决方案4】:

您可以使用 for 循环并遍历 cwd 中的每个文件并对所有文件执行相同操作,确保所有文件位于同一目录中

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

def valueSum(filename):
    columns = defaultdict(list)
    with open(filename) 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(filename)

    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)

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

    h = sum(b)

    print("the total actual cost(s) for team 11 is:", v)
    print("the total reported price for team 11 is:", h)

for filename in os.listdir("."):
    if filename.endswith(".csv"): #count only csv files
        valueSum(filename)

【讨论】:

  • 我收到了错误。 'ValueError: cannot convert float NaN to integer' 我认为它给出了这个错误,因为某些文件可能没有相同的格式。我也不确定 NaN 是什么。
  • 那是因为 csv 文件中的某些值是 NaN。检查它是否不是 NaN 然后转换为 int
  • 我不知道该怎么做,我可以使用某种功能吗?
  • 你可以用math.isnan()做到这一点,math.isnan(value) 如果它的 NaN 将返回 True,如果它不是 NaN 则返回 False
猜你喜欢
  • 1970-01-01
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 2017-08-28
  • 2021-09-17
  • 1970-01-01
  • 2010-10-12
  • 1970-01-01
相关资源
最近更新 更多