2

I'm trying to export rankings and URLs based on a specific keyword from Google and export it to a csv. Everything works fine except for the way my CSV file is composed.

My problem is that when I export my array to CSV, everything is on one row. I want it to be on 2 different columns and multiple rows.

I have tried adding '\n' inside the rank variable and it breaks the line in the terminal when I print the results, but inside the csv it appends the \n as a new value.

I tried adding newline='\n'to open() and it did break in the terminal but not in the csv export.

d=[]
for i in links:
    counter = counter + 1
    if sitename in str(i):
        url = i.find_all('a', href=True)
        position = "position: %d" % (counter)
        rank = "url: %s" % (url[0]['href'])
        d.append(position)
        d.append(rank)
        print(position, rank)


filename = "rank_export.csv"
f = open(filename,"w")
headers = "URL, Rank\n" 
f.write(headers)
f.write(str(d))
f.close()

1
  • 1
    We can convert to pandas, add headers and use python df.to_csv(index=False) Commented Apr 29, 2019 at 21:41

1 Answer 1

1

As far as I understand, you are appending both the position and the rank in the same list. Then you are writing that list in the csv, and thus the one-line output. You are also trying to pass the csv headers using a comma-separated string instead of a list of column names;

The following should do the trick for you:

import csv

with open('rank_export.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(['URL', 'Rank'])
    writer.writerows(zip(d[0::2], d[1::2]))
Sign up to request clarification or add additional context in comments.

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.