# Process census data, make .tsv file to upload to Many Eyes

censusFile = open('census.txt','r')

# Open file for writing. This creates the file in the folder that
# you're running the program in, or on the Desktop if you're
# running it on the Desktop.
vizFile = open('percent.tsv','w')

# First line of file should be names of columns in table.
vizFile.write('County\tState\tPercent Hispanic\n')

# Skip first two lines in census file
censusFile.readline()
censusFile.readline()

# The variable line exists but does not have anything in it...
line = None
while line != '':  # This is True if line = None, and also later.
    # It is False when we get to the end of the file and
    # the readline() method returns the empty string. 
    line = censusFile.readline()  # Read the next line of the file. 
    if line != '':  # If we are at the end, and there is no line,
        # don't process it! Otherwise all kinds of crazy errors!
        words = line.split('\t') # Split on tabs
        
        # Remove last word from name of county. 
        countyStr = words[0]
        countyWords = countyStr.split()
        county = ''
        for i in range( len(countyWords)-1):
            county = county+' '+countyWords[i]

        # Convert total population to a float
        totalStr = words[1]
        totalStr = totalStr.replace(',' , '')
        total = float(totalStr)

        # Convert number of Hispanics to a float
        hispanicStr = words[10]
        hispanicStr = hispanicStr.replace(',' , '')
        hispanic = float(hispanicStr)

        # Calculate percent hispanic
        percent = hispanic*100.0/total
        
        # print county, total, hispanic,percent
        # The expression:  '%.2f'%percent
        # produces a string with two decimal places.
        # We can put other stuff before or after the number
        # in the string, like here.
        # Try out converting a float to a string this way
        # in IDLE to see how it works. 
        vizFile.write(county+'\tCalifornia\t%.2f \n'%percent)

# Close files when done!
censusFile.close()
vizFile.close()
        

