I have a text file that has numerous lines. I want to extract certain lines and write them to a CSV file. However, I want to write particular lines to the same row in the CSV file. For example, my text file is like this:
Name= Sarah F
Location= Baltimore MD
Name= Bob M
Location= Sacramento CA
Name= Tom M NY
Location= Brooklyn NY
Name= Anne F
Location= Morristown NJ
My CSV file I want to generate will include the name of the person, their sex, the city and state they reside in:
Sarah,F,Baltimore,MD
Bob,M,Sacramento,CA
Tom,M,Brooklyn,NY
Anne,F,Morristown,NJ
When I use csv.writerows([list]) I get the names,sex and the city,state written in separate rows:
Sarah,F
Baltimore,MD
Bob,M
Sacramento,CA
Tom,M
Brooklyn,NY
Anne,F
Morristown,NJ
When I try to append to the list with: [name, sex] the city and state the override the original list instead of appending.
Here is my code to do this:
import csv
file = open("file_to_use.txt", 'r')
csv_file = open("file_to_write.csv", 'wb')
writer = csv.writer(csv_file)
Row_lines =[]
for line in file:
if line.startswith("Name="):
name_line = line.replace(" ", ",")
name_line = name_line.strip("\n")
Row_lines.append(name_line)
if line.startswith("Location="):
loc_line = line.replace(" ", ",")
loc_line = loc_line.strip("\n")
Row_lines.append(loc_line)
writer.writerows(Row_lines)
csv_file.close()
I know I have some logical order in the incorrect place, but I can't seem to figure it out.
Name=andLocation=lines always alternating in the input file? Are there any other lines in the input file or only those two types?