Python写入以类对象命名的csv,并在基于类对象的文件夹中找到

我正在研究一个项目,并创建一个脚本,该脚本根据在csv文件中找到的对象创建类,连接到API并下载数据,然后将这些数据放入以其中一个对象命名并在以下位置找到的csv文件中以对象命名的文件夹。

我创建了一个示例代码来说明我要执行的操作,但是出现一些错误并尝试了多种操作,但尚未找到解决方案。示例代码如下。

import csv
# class definition
class Person:
   def __init__(self, Name, City, Age):
       self.Name = Name
       self.City = City
       self.Age = Age

# using a list, because it's mutable
Persons = []

# reading csv and filling Persons list
with open('To_Download\\Testentitydownload.csv', mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        entity = Person(str(row["Name"]), str(row["City"]), str(row["Age"]))

        # add the new person to the list
        Persons.append(entity)

# writing to a csv file which is based on the Name of the Person, and found in the folder based on the City the Person lives in.
def print_to_file(*args):
    c = str(Person().City.__init__())
    n = str(Person().Name.__init__())
    with open('Entities\\'+c+'\\'+n+'.csv', 'a') as fh:
        fh.write(' '.join(map(str,args)))
        fh.write('\n')

write = print_to_file
Layout = "{!s:1} {!s:2} {!s:3}"
write(Layout.format("Name;", "City;", "Age;"))

# output loop, API stuff.
for person in Persons:
    write(str(person.Name), ";", str(person.City), ";", str(person.Age))
    Writer=csv.writer(csv_file)

我遇到的问题是我不确定如何写入以类对象命名的文件夹中找到的文件。尝试执行此操作的代码片段为:

# writing to a csv file which is based on the Name of the Person, and found in the folder based on the City the Person lives in.
def print_to_file(*args):
    c = str(Person().City.__init__())
    n = str(Person().Name.__init__())
    with open('Entities\\'+c+'\\'+n+'.csv', 'a') as fh:
        fh.write(' '.join(map(str,args)))
        fh.write('\n')

上面的代码产生错误:

TypeError:init()缺少3个必需的位置参数:“名称”,“城市”和“年龄”

我已经尝试了多种方法来使其工作,例如,删除了“ Person”中的“()”

c = str(Person().City.__init__())

产生错误

AttributeError:类型对象“ Person”没有属性“ City”

从两行中删除“ init()”,将导致相同的错误。

或在其中替换“ c”和“ n”

with open('Entities\\'+c+'\\'+n+'.csv', 'a') as fh:

with open('Entities\\'+str(Person.City)+'\\'+str(Person.Name)+'.csv', 'a') as fh:

这也会导致相同的错误。

我已经为此苦苦挣扎了一段时间,我希望这里有人可以帮助我让我的脚本将数据保存到这些位置,同时保持类似的脚本结构。

提前致谢!

评论