Hi, I seem to be having some trouble converting the output of this(which is a list) to a string of integers. What I want ultimately is for the output to just be integers. After that I also need to determine how many times an integer appears. I know I need to use the count function, but idk how to put it together. Example if the integer "10" appears four times I need an ouput that says it appears four times, and "9" appears 1 time, etc. Thanks!

file = open ('grade.txt', 'r')

s=file.readline()
grade=[]
while s[0:3]!="EOF":
    lst=s.split(',')
    if lst[0][0]!='I':
        grade.append(lst[5])
    print(lst)
    s=file.readline()

print(grade)

Dani AI

Generated

A robust, maintainable approach is to parse the file as CSV, locate the A1 column from the header (strip header cells first), clean each A1 cell (strip whitespace and trailing newline), drop any fractional part if truncation is intended, convert the cleaned token to an integer, then count occurrences with a Counter. This avoids the common pitfalls in the thread: calling append() and assigning its return value (which is None), trying to int() an entire list string, and failing on leading/trailing spaces or newline characters.

was right that int() is needed for integer values, and correctly showed the value-cleaning idea; the following example implements those ideas while adding reliable CSV parsing and counting (no reliance on multiple readline() calls, and header cells are stripped so column lookup is robust):

import csv
from collections import Counter

counts = Counter()
with open('grade.txt', newline='') as fh:
    reader = csv.reader(fh)
    header = [h.strip() for h in next(reader)]
    a1_idx = header.index('A1') if 'A1' in header else 5

    for row in reader:
        if not row:
            continue
        first = row[0].strip()
        if first.startswith('I') or first == 'EOF':
            continue
        raw = row[a1_idx].strip()
        if not raw:
            continue
        # truncate decimal part ("4.5" -> "4")
        intpart = raw.split('.')[0]
        try:
            grade_int = int(intpart)
        except ValueError:
            continue
        counts[grade_int] += 1

for grade, cnt in sorted(counts.items(), reverse=True):
    print(f"{grade} appears {cnt} time{'s' if cnt != 1 else ''}")

Notes: truncation (dropping the fractional part) discards information; if rounding is preferred, convert to float and round explicitly. Also treat malformed entries (non-numeric tokens) according to policy: either skip or log them for manual review.

Recommended Answers

All 7 Replies

use int(mystring)

Hi, yes i have tried the int(mystring), but I keep getting an "error invalid literal for int() with base 10"

file = open ('grade.txt', 'r')

s=file.readline()
grade=[]
while s[0:3]!="EOF":
    lst=s.split(',')
    if lst[0][0]!='I':
        x = grade.append(lst[5])
        y = str(x)
        z = int(y)
    print(lst)
    s=file.readline()

print(grade)    

And what is the type and value of the y? Line 9 does not make sense for me, because what is value of x after line 8?

sorry I just really need the output to be a string of integers

file = open ('grade.txt', 'r')

s=file.readline()
grade=[]
while s[0:3]!="EOF":
    lst=s.split(',')
    if lst[0][0]!='I':
        grade.append(lst[5])
        print(lst)
    s=file.readline()

print(grade)
string_grades = str(grade)
print(int(string_grades))

Based on previous post this is your output.
[' 6', ' 4.5', ' 10', ' 4', ' 10']

#print(grade)
#string_grades = str(grade)
print([float(i) for i in grade]) # [6.0, 4.5, 10.0, 4.0, 10.0]
print([i.strip() for i in grade]) #Clean string list ['6', '4.5', '10', '4', '10']
print(','.join([i.strip() for i in grade])) #Only string 6,4.5,10,4,10

You have made code worse,follow advice you did get in previous post.
http://www.daniweb.com/software-development/python/threads/439406/reading-a-.txt-file
Do not use readline() two times and do not use file as variable name,file is a reserved word used by python.

With some Pythonic power it can also look like this.

with open('grade.txt', 'r') as inFile:
    lst = [i.strip().split(',') for i in inFile]
    print [float(i) for i in lst[1][-5:]] #[6.0, 5.5, 8.0, 10.0, 8.5]

hi, yes the output i needed was the Assignment 1 grades(inside the list) which is why i put it into a list so i can extract the A1 grades. I just need the output [' 6', ' 4.5', ' 10', ' 4', ' 10'] to be (' 6', ' 4', ' 10', ' 4', ' 10') or a string, taking out the decimals,etc.

Something like this

['ID ', ' Last ', ' First', ' Lecture', ' Tutorial', ' A1', ' A2', ' A3', ' A4', ' A5\n']
['10034567', ' Smith', ' Winston', ' L01', ' T03', ' 6', ' 5.5', ' 8', ' 10', ' 8.5\n']
['10045678', ' Lee', ' Bruce', ' L02', ' T05', ' 4.5', ' 6.5', ' 7', ' 7', ' 8.5\n']
['00305678', ' Obama', ' Jack', ' L01', ' T05', ' 10', ' 10', ' 9', ' 9.5', ' 10\n']
['00567890', ' Brown', ' Palin', ' L02', ' T03', ' 4', ' 7.5', ' 6.5', ' 0', ' 5\n']
['10012134', ' Harper', ' Ed', ' L01', ' T03', ' 10', ' 9', ' 7.5', ' 10', ' 6.5\n']
['10014549', ' Johnson', ' Andrew', ' L01', ' T05', ' 10', ' 0', ' 10', ' 5.5', ' 7\n']
['10020987', ' Clockwork', ' Milan', ' L02', ' T03', ' 10', ' 8.5', ' 8', ' 9', ' 9\n']
['10021234', ' Freeman', ' Skyski', ' L01', ' T02', ' 0', ' 10', ' 10', ' 10', ' 8.5\n']
(' 6', ' 4', ' 10', ' 4', ' 10', ' 10', ' 10', ' 0')

I just need the output [' 6', ' 4.5', ' 10', ' 4', ' 10'] to be (' 6', ' 4', ' 10', ' 4', ' 10')

>>> lst = [' 6', ' 4.5', ' 10', ' 4', ' 10'] 
>>> [str(int(float(i))) for i in lst] 
['6', '4', '10', '4', '10']
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.