【问题标题】:How to write items in the same array on the row and for the next array skip a line and write the items on the next row in Python如何在行上的同一数组中写入项目并为下一个数组跳过一行并在Python中的下一行写入项目
【发布时间】:2016-06-09 21:22:10
【问题描述】:

`我目前在一个 CSV 中有一个名称列表,这些名称由 ["last name", "first name"] 分隔。如果没有名称,则数组只有 ["1"]。当前 CSV 上的每个名称都在其自己的单独数组中。我正在尝试在 CSV 中写入名称,以便一列是所有姓氏(和“1”),另一列是所有名字。

我当前的 CSV 看起来像

Names:
Wayne, Bruce
1
1
1
Parker, Peter 
Kent, Clark 

我希望我的 CSV 输出

Last Name:    First Name:
Wayne         Bruce
1
1
Parker        Peter
Kent          Clark            

在我当前的代码中,["1"] 后面的任何内容都在换行符上,但数组 ["last name", "first name"] 后面的任何内容都不是。有没有办法在我当前的代码中解决这个问题?

import re
import csv


trite = open('Lastfirststrip.csv', "r")
spamreader = csv.reader(trite)
twrite = open('LastFirst.csv', 'w')
spamwriter = csv.writer(twrite, delimiter=" ", lineterminator="\n",  skipinitialspace=True)
altwriter = csv.writer(twrite, delimiter=' ', lineterminator=',', skipinitialspace=True )

for column in spamreader:
    c = ","
    d = ",".join(column)
    e = re.findall('[A-Za-z]+',d)

    if len (e) == 1:
        for item in e:
            spamwriter.writerow([item])
    else:
        for item in e:
            altwriter.writerow([item])

【问题讨论】:

  • 您能否发布一个数据示例、它的外观以及期望的结果?我对描述有点迷茫。
  • ...我不相信您的输入格式是 CSV。

标签: python arrays csv


【解决方案1】:

这个问题的感觉是“我有一把锤子,所以一切看起来都像钉子。”

您正在尝试使用 csv 模块来做一些不完全是 csv 的事情。

with open("/tmp/input") as fdin, open("/tmp/o", "w") as fdout:                  
    for line in fdin:                                                           
        line = line.strip()                                                     
        if line == "1":                                                         
            print >> fdout, line                                                
            continue                                                            
        if line == "Names:":                                                    
            print >> fdout, "Last Name:\tFirst Name:"                           
            continue                                                            
        first, last = line.split(",")                                           
        print >> fdout, first.strip() + "\t" + last.strip()     

【讨论】:

    猜你喜欢
    • 2023-01-09
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2023-04-02
    • 2015-01-12
    相关资源
    最近更新 更多