2

I am a newbie at Python & I have a web scraper program that retrieved links and puts them into a .csv file. I need to add a new line after each web link in the output but I do not know how to use the \n properly. Here is my code:

  file = open('C:\Python34\census_links.csv', 'a')
  file.write(str(census_links))  
  file.write('\n')
C McCown
  • 67
  • 1
  • 7

2 Answers2

3

Hard to answer your question without knowing the format of the variable census_links.

But presuming it is a list that contains multiple links composed of strings, you would want to parse through each link in the list and append a newline character to the end of a given link and then write that link + newline to the output file:

file = open('C:/Python34/census_links.csv', 'a')

# Simulating a list of links:
census_links = ['example.com', 'sample.org', 'xmpl.net']

for link in census_links: 
    file.write(link + '\n')       # append a newline to each link
                                  # as you process the links

file.close()         # you will need to close the file to be able to 
                     # ensure all the data is written.
E. Ducateme
  • 4,028
  • 2
  • 20
  • 30
2

E. Ducateme has already answered the question, but you could also use the csv module (most of the code is from here):

import csv

# This is assuming that “census_links” is a list
census_links = ["Example.com", "StackOverflow.com", "Google.com"]
file = open('C:\Python34\census_links.csv', 'a')
writer = csv.writer(file)

for link in census_links:
    writer.writerow([link])
wdt12
  • 404
  • 2
  • 9