【问题标题】:Python - Write each item from a dict's key to a new linePython - 将字典键中的每个项目写入新行
【发布时间】:2020-04-11 16:58:23
【问题描述】:

我认为这应该相当简单,但我找不到适合我情况的写入解决方案。我有字典,每个键都有一个列表。对于字典中的每个键,我想打开一个 csv 文件并将每个列表中的每个项目写入一个新行。当程序循环遍历 dict 时,会为每个键创建一个新的 csv 文件,该键的列表中每个项目的行被写入 csv,然后 csv 关闭,以便可以为下一个键创建下一个 csv :

for k, v in Dict.items():
    name = "coQ" + str(k) + ".csv"
    cPath = r"C:\Path"
    coQ = os.path.join(cPath, name)
    company_file = open(coQ, 'w')
    for i in v:
        company_file.write(str(i))
    company_file.close()

这会将列表写入 csv,但所有列表项都在 csv 输出中的同一行。我尝试使用 append 'a' 打开,但我得到了相同的结果,我认为换行符不会起作用,因为它不是新行而是列表中需要写入的项目。

【问题讨论】:

  • 只需在文件中写一个换行符:company_file.write(str(i)+"\n")

标签: python csv dictionary


【解决方案1】:

试试:

for k, v in Dict.items():
    name = "coQ" + str(k) + ".csv"
    cPath = r"C:\Path"
    coQ = os.path.join(cPath, name)
    company_file = open(coQ, 'w')
    for i in v:
        company_file.write("\n")
        company_file.write(str(i))
    company_file.close()

或者正如帕特里克所说:

for k, v in Dict.items():
    name = "coQ" + str(k) + ".csv"
    cPath = r"C:\Path"
    coQ = os.path.join(cPath, name)
    company_file = open(coQ, 'w')
    for i in v:
        company_file.write(str(i)+'\n')
    company_file.close()

【讨论】:

    猜你喜欢
    • 2012-01-30
    • 2017-10-03
    • 2012-11-19
    • 1970-01-01
    • 2016-12-10
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    相关资源
    最近更新 更多