The following code is what I have written to read data from a website and store it in a list. The code works, but it also throws a list out of range error regardless. Can anybody explain what I'm doing wrong?
import urllib.request
data_url = "http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data"
aboveFifty = 0
belowFifty = 0
""" The variables for storage """
age = 0
worksFor = ""
college = ""
salary = ""
bools = True
try:
print("Retrieving the data... ")
local_file, headers = urllib.request.urlretrieve(data_url)
print("Data retrieved")
fh = open(local_file, "r")
print("Reading the file... ")
for row in fh:
table = [row.strip().split(" ")]
salary = table[0][14]
if bools == True:
print("Table: ", table)
bools = False
if salary == "<=50K":
belowFifty += 1
elif salary == ">50K":
aboveFifty += 1
except IOError as e:
print("IO Error: ", e)
except IndexError as ie:
print("Index error: ", ie)
print("Above fifty: ", aboveFifty, "Below fifty: ", belowFifty)
fh.close()
The traceback error I get is:
Traceback (most recent call last):
File "C:\Users\Killian\workspace\College\Assignment.py", line 25, in <module>
salary = table[0][14]
IndexError: string index out of range
Your data is corrupt. Specifically, there is a blank line at the end of your data file. You can work with the corrupt data like so:
for row in fh:
table = [row.strip().split(" ")]
if not table:
continue # <-- ignore blank lines
salary = table[0][14]
Related
I had to run a Code to lookup entries and produce a database Then run a different code to read the database and produce where.js.
But everytime I run the second code it gives me a Traceback:
Traceback (most recent call last):
File "c:\Users\dylan\OneDrive\Documents\geodata\geodata\geodump.py", line 8, in <module>
cur.execute('SELECT * FROM Locations')
sqlite3.OperationalError: no such table: Locations
if anyone can help it would be appreciated I'll leave the code below:
import sqlite3
import json
import codecs
conn = sqlite3.connect('geodata.sqlite')
cur = conn.cursor()
cur.execute('SELECT * FROM Locations')
fhand = codecs.open('where.js', 'w', "utf-8")
fhand.write("myData = [\n")
count = 0
for row in cur :
data = str(row[1].decode())
try: js = json.loads(str(data))
except: continue
if not('status' in js and js['status'] == 'OK') : continue
lat = js["results"][0]["geometry"]["location"]["lat"]
lng = js["results"][0]["geometry"]["location"]["lng"]
if lat == 0 or lng == 0 : continue
where = js['results'][0]['formatted_address']
where = where.replace("'", "")
try :
print(where, lat, lng)
count = count + 1
if count > 1 : fhand.write(",\n")
output = "["+str(lat)+","+str(lng)+", '"+where+"']"
fhand.write(output)
except:
continue
fhand.write("\n];\n")
cur.close()
fhand.close()
print(count, "records written to where.js")
print("Open where.html to view the data in a browser")
Like the title says, I've being working on a variant of Conway's Game of Life in python that can read a "world" from a file and generate the starting world from that. However, in my code, I'm being given a "string index out of range" issue at the line while(aLine[currentCharacter] != NEWLINE), and I can't figure out why.
If it helps, in the input files " " is treated as a dead cell, and "*" is treated as a living cell.
Thank you for the help and please let me know if there's any additional info I should provide
def fileReadWorld():
fileOK = False
world = []
row = 0
column = 0
while (fileOK == False):
try:
filename = input("Name of input file: ")
inputfile = open(filename,"r")
fileOK = True
aLine = inputfile.readline()
if(aLine == ""):
print("The file %s" %(filename), "is empty.")
fileOK = False
else:
aLine = inputfile.readline()
row = 0
while(aLine != ""):
currentCharacter = 0
world.append([])
while(aLine[currentCharacter] != "\n"):
world[row].append(aLine[currentCharacter])
currentCharacter = currentCharacter + 1
row = row + 1
aLine = inputfile.readline()
inputfile.close()
maxRows = row
maxColumns = len(world[0])
return(world, maxRows, maxColumns)
except IOError:
print("Problem reading from file %s" %(filename))
fileOK = False
The input file I am using is
*
*
***
(it should display as a 10x10 grid)
Consider this simpler solution with the same result:
def main():
world = []
while True:
try:
filename = input("Name of input file: ")
for aLine in open(filename,"r")
world.append(list(aLine[:-1]))
if world:
maxRows = len(world)
maxColumns = len(world[0])
return world, maxRows, maxColumns
print("The file %s" %(filename), "is empty.")
except IOError:
print("Problem reading from file %s" %filename)
print(main())
I have a program where I encrypt class.__dict__ and save it to a file in an array so the file looks something like this -
{'some name':[1, 2, 3],
'data':'''9ÈX§Ë¡¡Ö© îo[ y^5Ð¥"¢§«!fa¥mc^W''' #somthing like this but a lot longer
}
I then read it and need to decrypt data but before that, I need to get the data from the array that is currently a string which I did with eval(fileContent) and it gives me the error -
Traceback (most recent call last):
File "C:/Users/stemb/Documents/programing/python/programs/img editor/__init__.py", line 127, in
<module>
main()
File "C:/Users/stemb/Documents/programing/python/programs/img editor/__init__.py", line 102, in main
save_code.auto_save_load()
File "C:\Users\stemb\Documents\programing\python\programs\img editor\save_code.py", line 153, in
auto_save_load
data = eval(fileContent)
ValueError: source code string cannot contain null bytes
My reading function is this
data = open("./save." + GLOBAL.fileType, "r", encoding="utf-8").read()
json.loads gives json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
My code is -
# imports
import json
import random
import time
print("Finished save_progress imports")
def encrypt(obj, log=0): #encrypt
# set data
data = str(obj.__dict__)
key = "codeAsciEightAndMabyA_Seven" + str(time.time()) # crate key
key = list(key)
random.shuffle(key) # randomize key
cryptionKeys = list()
encrypted = list()
iMinus = 0
for i in range(len(data)): # create a random + or - for extra security
cryptionKeys.append(random.choice(("+", "-")))
# encode part
for i, c in enumerate(data):
# set individual data
charAsci = ord(c)
cryptionKey = cryptionKeys[i]
done = 0
while done == 0:
try:
charKey = ord(key[i - iMinus])
done = 1
except IndexError:
iMinus += len(key)
if cryptionKey == "+":
encryptedOrd = charAsci + charKey
else:
encryptedOrd = charAsci - charKey
if encryptedOrd < 0:
encryptedOrd += 110000
cryptionKeys[i] = "="
cryptionKey = cryptionKeys[i]
encryptedChar = chr(encryptedOrd)
encrypted.append(encryptedChar)
if log == 1:
print("charNumb \/")
print(i)
print("charAsci \/")
print(charAsci)
print("cryptionKey \/")
print(cryptionKey)
print("charKey \/")
print(charKey)
print("encryptedOrd \/")
print(encryptedOrd)
print("encryptedChar \/")
print(encryptedChar)
print()
encrypted2 = encrypted
encrypted = ""
for c in encrypted2:
encrypted += c
return str(encrypted), str(key), str(cryptionKeys)
def auto_save(GLOBAL): # the save func
file = open("./save." + GLOBAL.fileType, "w", encoding="utf-8")
encryptedGLOBAL, key, cryptionKeys = encrypt(GLOBAL)
out = ("{'key':" + str(key) + ", 'cryptionKeys':" + str(cryptionKeys) + ", 'data':'''" + str(
encryptedGLOBAL) + "'''}")
print(out)
file.write(out)
file.close()
def auto_save_load(aclass): # the loading dunc
data = open("./save." + GLOBAL.fileType, "r", encoding="utf-8").read()
data = eval(data)
key = data["key"]
cryptionKeys = data["cryptionKeys"]
encryptedGLOBAL = data["data"]
print(key)
print()
print(cryptionKeys)
print()
print(encryptedGLOBAL)
Other answers have said to remove the null bytes but the encryption method needs them.
Please help.
A hotel salesperson enters sales in a text file. Each line contains the following, separated by semicolons: The name of the client, the service sold (such as Dinner, Conference, Lodging, and so on), the amount of the sale, and the date of that event. Write a program that reads such a file and displays the total amount for each service category. Display an error if the
My text file contains
Bob;Dinner;10.00;January 1, 2015
Tom;Dinner;14.00;January 2, 2015
Anne;Lodging;125.00;January 3, 2015
Jerry;Lodging;125.00;January 4, 2015
so here is my code so far
def main():
file_name = input("Input file name: ")
amount_by_category = process_file(file_name)
if amount_by_category:
print 'Totals:'
for key in amount_by_category:
print '{0}: $ {1}'.format(key, amount_by_category.get(key) )
def process_file(file_name):
infile = open(file_name, 'r')
# a dictionary mapping category to total amount for that category
amount_by_category = {}
for line in infile:
fields = line.split(';')
if len(fields) != 4:
raise Exception('Expected 4 fields but found %s' % len(fields))
value = float(fields[2])
category = fields[1]
if not category in amount_by_category:
amount_by_category[category] = 0.0
amount_by_category[category] += value
return amount_by_category
main()
I'm getting a syntax error and not sure why.
And the traceback:
Traceback (most recent call last):
File "C:\Users\Brandon\Desktop\Assignment 7\girrrr.py",
line 24, in <module> main() File "C:\Users\Brandon\Desktop\Assignment 7\girrrr.py",
line 7, in main print ('{0}: $ {1}').format(key, amount_by_category.get(key) )
AttributeError: 'NoneType' object has no attribute 'format'
It looks like you're using an old python, but this code works just fine in 3.6:
def main():
file_name = input("Input file name: ")
amount_by_category = process_file(file_name)
if amount_by_category:
print ("Totals:")
for key in amount_by_category:
print ("{}: $ {}".format(key, amount_by_category.get(key)))
def process_file(file_name):
infile = open(file_name, 'r')
# a dictionary mapping category to total amount for that category
amount_by_category = {}
for line in infile:
fields = line.split(';')
if len(fields) != 4:
raise Exception('Expected 4 fields but found %s' % len(fields))
value = float(fields[2])
category = fields[1]
if not category in amount_by_category:
amount_by_category[category] = 0.0
amount_by_category[category] += value
return amount_by_category
main()
The traceback you have shared looks like this:
print ('{0}: $ {1}').format(key, amount_by_category.get(key) )
while you code looks like this:
print '{0}: $ {1}'.format(key, amount_by_category.get(key) )
I tried running your code, It runs fine. Try re-running the code, It should work.
def isexact(pat):
for c in pat.upper():
if c not in 'ATGC':
return 0
return 1
def print_matches(ofh, enz, matches):
if matches:
print >>ofh, "Enzyme %s matches at:" % enz,
for m in matches:
print >>ofh, m,
print >>ofh
else:
print >>ofh, "No match found for enzyme %s." % enz
def get_site_only(pat):
newpat = ""
for c in pat:
if c.isalpha():
newpat += c
return newpat
def findpos(seq, pat):
matches = []
current_match = seq.find(pat)
while current_match != -1:
matches.append(current_match)
current_match =seq.find(pat, current_match+1)
return matches
seq = ""
ifh = open("C:\Python27\\link_cutzymes.txt",'r')
ofh = open("C:\Python27\\re-en-output.txt", "w")
line = ifh.readline()
while line:
fields = line.split()
name = fields[0]
pat = get_site_only(fields[2])
if isexact(pat):
print_matches(ofh, name, findpos(seq, pat))
line = ifh.readline()
else:
line = ifh.readline()
ofh.close()
ifh.close()
it is showing list index error can help me
Traceback (most recent call last): File
"C:/Users/ram/Desktop/rest_enz7.py", line 55, in
name = fields[0] IndexError: list index out of range
name = fields[0] - you probably are reading an empty line, splitting it, and accessing it at index 0, which is out of range for an empty list..
you can make sure your file contains only lines of your format, check for empty lines in the code, or use try and except to name a few options.
while reading the data from file,if data is not exist to split,it will not convert into list. I can see in your code name = fields[0] is causing error.
At that time please use try and except in your code.
you can rewrite the code as :
try:
fields = line.split()
name = fields[0]
except:
pass
What a string[x] does is get the xth letter of the list. This means that if there is no object in the xth position then you get an error.
So if name = fields[0] returns an error then fieldsmust be an empty list (It would look like this: []) because there is no first object (Python counts from zero so letter 0 is letter 1, letter 1 is letter 2 and so on). You can fix this with a try: and except: like so:
try:
name = fields[0]
except:
name = '' #Or whatever code you want to run if it fails
In the place of name = fields[0]