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')
0

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

4 Comments

print(x, file=f) is another way to do f.write(x + '\n').
@MadPhysicist ... what you say is definitely true, thanks for sharing. I opted to try to stay as close to the OP's original code layout as I could to minimize the cognitive load.
That's probably a good idea. I'll just leave the comment here for posterity.
Thank you so much! These were in a set but this worked perfectly.
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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.