0
#first import the csv module
import csv

#open the text file in read mode
text_file = open("randomaddresses.txt","r")
for line in text_file:
    line.rstrip("\n")
    

#open a csv file in write mode
csv_file = open("randomaddresses.csv", "w")
reader = csv.reader(text_file, delimiter= ",")
writer = csv.writer(csv_file)
writer.writerow(["Address","City","State","Zip Code"])
for row in reader:
    writer.writerow(row)


#close the two files
text_file.close()
csv_file.close()

I'm trying to get my code to show output in the csv file but when I open it up all I get is my first row but none of the addresses show up.

the data in the text file is this:
371 Arch Street
Cranford, NJ 07016
679 Race Street
Lockport, NY 14094
579 7th Avenue
Santa Clara, CA 95050
12 West Street
Orange Park, FL 32065
906 2nd Street West
Great Falls, MT 59404
851 Locust Lane
Lombard, IL 60148
837 Fawn Court
Centereach, NY 11720
343 Jefferson Court
Norwalk, CT 06851
34 3rd Street North
Athens, GA 30605
143 10th Street
North Wales, PA 19454

I would like to get each one in a cell in excel under the Address,City,State,and Zip heading.

Michael Ruth
  • 2,112
  • 14
  • 19
  • Is the text file very *uniform*? Two lines per address? – wwii Mar 15 '21 at 20:18
  • `for line in text_file: line.rstrip("\n")` really doesn't do anything. Try commenting it out. – wwii Mar 15 '21 at 20:20
  • To WWii I did comment it out but I have space below the address and above it plus it doesn't align under my headings Address,City,State and Zip. –  Mar 15 '21 at 20:32
  • Well, that sounds like a different problem. We closed this one as a duplicate so you will have to ask another - you should search around first though. When you write the new csv file the column alignment doesn't matter - the comma delimits the fields. – wwii Mar 15 '21 at 20:36
  • Ok thanks for the advice. –  Mar 15 '21 at 20:40
  • For the extra blank lines, there is a statement in [the documentation](https://docs.python.org/3/library/csv.html#csv.writer) - `If csvfile is a file object, it should be opened with newline=''` – wwii Mar 15 '21 at 20:43
  • https://docs.python.org/3/library/csv.html#id3 – wwii Mar 15 '21 at 20:44
  • Thanks for that –  Mar 15 '21 at 20:47
  • Have you tried pandas or datatable to work with csv files? It is especially a good approach if your data fits a tabular format. Based on your sample it looks like it does. – peter Apr 07 '21 at 20:59

0 Answers0