`I currently have a list of names in one CSV that are separated ["last name", "first name"]. If there is no name, the array just has ["1"]. Each name on the current CSV is in its own separate array. I'm trying write the names in a CSV so that one column is all last names (and "1's") and the other column is all first names.
My Current CSV looks like
Names:
Wayne, Bruce
1
1
1
Parker, Peter
Kent, Clark
I want my CSV to Output
Last Name: First Name:
Wayne Bruce
1
1
Parker Peter
Kent Clark
With my current code, anything following a ["1"] is going on a newline, but anything following an array ["last name", "first name"] isn't. Is there any way to fix this in my current code?
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])
This question has the feel of "I have a hammer, so everything looks like a nail."
You're trying to use the csv module to do something that isn't exactly 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.