I am learning python so this might sound simple, I am trying to run the code below but I keep getting the error message shown, any thoughts on what could be causing it?
from geopy import geocoders
import csv
g_api_key = 'my_google_api_key'
g = geocoders.GoogleV3(g_api_key)
costco = csv.reader (open('costcolimited.csv'), delimiter = ',')
# Print header
print "Address, City, State, Zip Code, Latitude, Longitude"
for row in costco:
full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4]
place, (lat,lng) = list (g.geocode(full_addy, exactly_one=FALSE))[0]
full_addy + "," + str(lat) + "," + str(lng)
The error I am getting
Traceback (most recent call last):
File "C:\Python27\geocodelocations.py", line 12, in <module>
full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4]
IndexError: list index out of range
The error is caused by referring element out of list range. From your code, it is probably because you start counting element from 1. Remember that in python list, index starts from 0. If this is your situation, then shift indexes in
full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4]
to
full_addy = row[0]+ "," + row[1]+ "," + row[2] + "," + row[3]
Otherwise, check your data structure and make sure it is matched with your code.
Thanks
First of all make sure your CSV file has four columns. Try checking if len(row) >= 4. If it contains you can go on with your code, but the first item in a Python list is referenced by 0 index.
Try something like this:
for row in costco:
if len(row) < 4:
print "Invalid file!"
break
full_addy = row[0]+ "," + row[1]+ "," + row[2] + "," + row[3]
place, (lat,lng) = list (g.geocode(full_addy, exactly_one=FALSE))[0]
full_addy + "," + str(lat) + "," + str(lng)
Related
I have a long line of code that prints a bunch of symbols for graphics, and I just started getting an index out of range error. it is inside a function, and this the code that matters:
at top, after imports(fr termcolor cprint, colored , time, os, random)
rannum = random.randrange(1,20,1)
the function:
def obstacle():
rocknum = random.randrange(0,12,1)
rock = ["on_cyan","on_cyan","on_cyan","on_cyan","on_cyan","on_cyan","on_cyan","on_cyan","on_cyan","on_cyan","on_cyan","on_cyan"]
rock[rocknum]= "on_cyan"
ongroundls = [" "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "] #runframe 1 list
pos = rannum
#print(rannum)
if rannum == random.randrange(0,20,1):
#print(rannum, pos)
ongroundls[rannum] = "4"
rock[rocknum] = "on_yellow"
else:
rock[rocknum] = "on_cyan"
#print(colored(ongroundls[0],"grey","on_cyan")+colored(ongroundls[1],"grey","on_cyan")+colored(ongroundls[2],"grey","on_cyan")+colored(ongroundls[3],"grey","on_cyan")+colored(ongroundls[4],"grey","on_cyan")+colored(ongroundls[5],"grey","on_cyan")+colored(ongroundls[6],"grey","on_cyan")+colored(ongroundls[7],"grey","on_cyan")+colored(ongroundls[8],"grey","on_cyan")+colored(ongroundls[9],"grey","on_cyan")+colored(ongroundls[10],"grey","on_cyan")+colored(ongroundls[11],"grey","on_cyan")+colored(ongroundls[12],"grey","on_cyan")+colored(ongroundls[13],"grey","on_cyan")+colored(ongroundls[14],"grey","on_cyan")+colored(ongroundls[15],"grey","on_cyan")+colored(ongroundls[16],"grey","on_cyan")+colored(ongroundls[17],"grey","on_cyan")+colored(ongroundls[18],"grey","on_cyan")+colored(ongroundls[19],"grey",rock[0])+colored(ongroundls[20],"grey",rock[1])+colored(ongroundls[21],"grey",rock[2])+colored(ongroundls[22],"grey",rock[3])+colored(ongroundls[23],"grey",rock[4])+colored(ongroundls[24],"grey",rock[5])+colored(ongroundls[25],"grey",rock[6])+colored(ongroundls[26],"grey",rock[7])+colored(ongroundls[27],"grey",rock[8])+colored(ongroundls[28],"grey",rock[9])+colored(ongroundls[29],"grey",rock[10])+colored(ongroundls[30],"grey",rock[11])+colored(ongroundls[31],"grey",rock[12]))
while pos > 19:
ongroundls[pos] = "#"
pos - 1
if pos == random.randrange(0, 32, 1):
pos == random
print(colored(ongroundls[0],"grey","on_cyan")+colored(ongroundls[1],"grey","on_cyan")+colored(ongroundls[2],"grey","on_cyan")+colored(ongroundls[3],"grey","on_cyan")+colored(ongroundls[4],"grey","on_cyan")+colored(ongroundls[5],"grey","on_cyan")+colored(ongroundls[6],"grey","on_cyan")+colored(ongroundls[7],"grey","on_cyan")+colored(ongroundls[8],"grey","on_cyan")+colored(ongroundls[9],"grey","on_cyan")+colored(ongroundls[10],"grey","on_cyan")+colored(ongroundls[11],"grey","on_cyan")+colored(ongroundls[12],"grey","on_cyan")+colored(ongroundls[13],"grey","on_cyan")+colored(ongroundls[14],"grey","on_cyan")+colored(ongroundls[15],"grey","on_cyan")+colored(ongroundls[16],"grey","on_cyan")+colored(ongroundls[17],"grey","on_cyan")+colored(ongroundls[18],"grey","on_cyan")+colored(ongroundls[19],"grey",rock[0])+colored(ongroundls[20],"grey",rock[1])+colored(ongroundls[21],"grey",rock[2])+colored(ongroundls[22],"grey",rock[3])+colored(ongroundls[23],"grey",rock[4])+colored(ongroundls[24],"grey",rock[5])+colored(ongroundls[25],"grey",rock[6])+colored(ongroundls[26],"grey",rock[7])+colored(ongroundls[27],"grey",rock[8])+colored(ongroundls[28],"grey",rock[9])+colored(ongroundls[29],"grey",rock[10])+colored(ongroundls[30],"grey",rock[11])+colored(ongroundls[31],"grey",rock[12]))
in while loop (buffer is just a small delay and a os.system('cls')
obstacle()
buffer()
rannum = random.randrange(1,20,1)
it was working fine, then I made some minor changes and i cannot seem to fix it. i have tried changing the randrange, and some things are commented out in an attempt to fix it. , so the numbers are not what they were when the problem started. What could I do to fix it?
Your problem is the final line. You hard-coded rock[12] at the end of the print, but rock only has 12 elements, so the last valid index is 11.
As I noted in the comments, even if you fix this, the code is borked; your while loop will either never run, or never exit, because you never change pos within the loop (pos - 1 computes a new value, but never stores it; pos -= 1 is perhaps the intent).
Here is a sample of my current code
for i in pin:
i.click()
time.sleep(4)
f = driver.find_elements_by_xpath('//td[#class="bold"]')
d = driver.find_elements_by_xpath('//td[#class="date"]')
with open("tennisopening.csv","a") as r:
r.write(match + "," + date + "," + score + "\n")
for i in f:
b= i.text
for i in d:
c= i.text
with open("tennisopening.csv","a") as r:
r.write(b + "," + c)
This results in a csv table with cells in the following order:
(b,c,match,date,score,\n)
But, I wish to have it in the following order:
(match,date,score,b,c,\n)
How can I fix this?
Thank you
for i in pin:
i.click()
time.sleep(4)
f = driver.find_elements_by_xpath('//td[#class="bold"]')
d = driver.find_elements_by_xpath('//td[#class="date"]')
with open("tennisopening.csv","a") as r:
for i in f:
b= i.text
for i in d:
c= i.text
with open("tennisopening.csv","a") as r:
r.write(b + "," + c)
r.write(match + "," + date + "," + score + "\n")
This will do
Remember when u write using
with open(filename,mode) as f:
f.write(data)
## data is written only in memory and not yet committed to file.
## data now committed to file
so for the data to be written you must come out of with open() scope
same goes for above data
First come out of this with's scope
with open("tennisopening.csv","a") as r:
r.write(b + "," + c)
and then write into memory
r.write(match + "," + date + "," + score + "\n")
Then come out of parent with scope
;)
Change your inner loop code with this:
with open("tennisopening.csv","a") as r:
for i in f:
b= i.text
for i in d:
c= i.text
r.write("{},{},{},{},{}\n".format(match,date,score,b,c)
This should write "match,date,score,b,c\n" in every line as you asked.
In your code, (match, date, score) will be written only once for every outer loop code.
And you have two instances open for the same file, the instance which writes "b,c" closes first, so it gets written first in the actual file.
I have two lists:
D1=[["a "," "," "," "," "," "],["b "," ","o"," "," "," "],["c ","x"," "," "," "," "],["d "," "," "," "," "," "],["e "," "," "," "," "," "]]
D2=[["a "," ","o"," ","x"," "],
["b "," "," "," "," "," "],["c "," "," "," "," "," "],["d "," "," "," "," "," "],["e "," "," "," "," "," "]]
D=[]
I want to make a list D so,D[i]=D1[i] + D2[i],for example the first element(list) looks like this:
D=[["a "," "," "," "," "," ","a "," ","o"," ","x"," "],...]
Please help me I am new in python
Try this:
D = [i+j for i,j in zip(D1,D2)]
if lengths are different it will cut the rest and go forward to the minimum of D1, D2. if you want the opposite, use zip_longest, like this:
from itertools import zip_longest
D = [i+j for i,j in zip_longest(D1,D2)]
But both will work if D1 and D2 have the same length.
Straightforward from your will (D[i] = D1[i] + D2[i]), the simplest way is to use comprehension lists. Asumming len(D1) == len(D2), :
D = [ D1[i] + D2[i] for i in range(len(D1)) ]
will do the job.
First copy D1 to D, if you don't want to alter D1. Then use extend method in python. It'll add all elements of list2 to list1.
Here is a simple code: though the time complexity of this code is O (n^2), it can be improved.
D1=[["a "," "," "," "," "," "],["b "," ","o"," "," "," "],["c ","x"," "," "," "," "],["d "," "," "," "," "," "],["e "," "," "," "," "," "]]
D2=[["a "," ","o"," ","x"," "],
["b "," "," "," "," "," "],["c "," "," "," "," "," "],["d "," "," "," "," "," "],["e "," "," "," "," "," "]]
D = D1 [:]
for i in range (len (D)):
D[i].extend (D2 [i])
print D
I'm new to scripting in python. I am extracting data from a tab delimited vcf file. My script works, but I have tried to concatenate the strings into a list using word[0:2] but this doesn`t work, so instead I add the data by splitting it manually:
i.e: word[0] + "\t" + word[1] + "\t" + word[2]
I am not sure why I have to do this as when I use lst = word[0:2] the command returns "can only concatenate list (not "str") to list. Why is this?
My entire code is:
lst = []
for line in my_file:
if 'chr' in line:
word = line.split("\t")
adp = word[7].split(";")
pc = word[9].split(":")
s = adp[0].split("=")
lst = word[0] + "\t" + word[1] + "\t" + word[3] + "\t" + word[4] + "\t" + s[1] + "\t" + pc[6] + "\n"
outputfile.write(lst)
How can I make this more concise?
Thanks
Use join when concatenating strings:
lst = []
for line in my_file:
if 'chr' in line:
word = line.split("\t")
lst.extend(word[7].split(";"))
lst.extend(word[9].split(":"))
lst.extend(adp[0].split("="))
out = '\t'.join(lst)
outputfile.write(out)
Can you help me to modify this code to writing out numbers to 2 decimal places in a cvs file?
outfile = open("numbers.csv", "a")
outfile.write(str(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')) + "," + str(number_1) + "," + str(number_2) + "," + str(number_3)+ "," + str(number_4) + "," + str(number_5) + "," + str(number_6) + "," + str(number_7) + "," + str(number_8) + "," + str(number_9) +"\n")
Thanks a lot.
Use the round() function before writing to the csv ,the second parameter to the round function is the number of decimal places to round-off to.
Example -
>>> number_1 = 1.4412324
>>> number_2 = 1.54988312
>>> round(number_1,2)
1.44
>>> round(number_2,2)
1.55
In your case -
outfile = open("numbers.csv", "a")
outfile.write(str(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')) + "," + str(round(number_1, 2)) + "," + str(round(number_2, 2)) + "," + str(round(number_3, 2))+ "," + str(round(number_4, 2)) + "," + str(round(number_5, 2)) + "," + str(round(number_6, 2)) + "," + str(round(number_7, 2)) + "," + str(round(number_8, 2)) + "," + str(round(number_9, 2)) +"\n")
You can consider using format
"{:.2f}".format(24.45679)
gives you '24.46'.