【问题标题】:Python - Write an array to csv / txt and then readPython - 将数组写入 csv / txt 然后读取
【发布时间】:2017-11-21 18:17:29
【问题描述】:

所以如果我有以下代码:

database = []
Name = input("What's the members name?")
MT = input("What membership type?")
DOB = input("What is the member DOB?")
DJ = (now.day ,"/" , now.month, "/", now.year)
year1 = int(now.year)
month1 = int(now.month)
day1 = int(now.day)
ry = int(year1 + 1)
rm = month1
rd = day1
renewal = (day1, month1, year1 + 1)
details = ["Name:",  Name, "Membership Type:", MT, "Date of Birth:", DOB, "Date Joined:", DJ,"Renewal Date:", renewal, "Renewal Year:", ry]
database.append(details)
menu()  

我将如何将(数据库)保存到文本文件/csv 文件以供以后读取。
我试过泡菜,但问题是我需要能够将数组的每个部分分开。
例如,如果我输入:

print(database[1])

我将返回所有存储为“名称”的名称,但是如果我在带回文件时使用 pickle 编写文件,那么

print (database[1])

现在显示添加的第二个用户的全部内容。我需要能够保存(数据库)并在读回时以相同的格式保存它。 使用 JSON 或 Pickle 的预期输出(假设第一个用户输入的名称为“Jeff”,第二个输入的名称为“John”)

print (database[1])

Jeff
John

实际输出:

["Name:",  John, "Membership Type:", MT, "Date of Birth:", DOB, "Date Joined:", DJ,"Renewal Date:", renewal, "Renewal Year:", ry]
  • 对不起,我是 python 新手。

【问题讨论】:

  • 你有很多选择。您可以使用 JSON 转储您的 dict,或使用 DictWriter 转储为 csv。
  • 我试过这个,但我遇到了和泡菜一样的问题?任何建议
  • 我不明白你的问题到底是什么。您可以发布输出(回读时)和您的预期输出吗?
  • 用预期和实际更新了帖子
  • @Jonathan。为什么预期的输出会打印 两个 名称?目前,database 是一个列表列表,因此要获取第一条记录的第二个元素,您应该执行print(database[0][1]) - 这将输出John

标签: python csv text


【解决方案1】:

您似乎正在创建一个记录数组。尝试以这种方式访问​​数据:

print(database[0][1])    #[0] for the first record, [1] for second item
print(database[1][1])    #second user, second item

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多