简体   繁体   中英

Python, AttributeError: 'int' object has no attribute 'strip'

I want to extract data from a txt file in a simple dictionary structure (or a class), but I get the following error code:

AttributeError: 'int' object has no attribute 'strip'

The full Python code can be found in the answers!!!

The code that I used:

data = []

file = open("fruits.txt", "r", encoding="utf-8")
lines = file.readlines()

#I did it two ways

#Dictionary:
for i in lines:
    data_line = i.strip().split(";")
    data_line[2] = data_line[2].replace(",", ".") ## ! ##
    dictionary = {
        "fruit": data_line[0],
        "piece": int(data_line[1]),
        "price": float(data_line[2]) ## ! ##
    }
    data.append(dictionary)
file.close()

#and
#Class:
class fruits:
    def __init__(self, fruit, piece, price ):
        self.fruit = fruit
        self.piece = int(piece)
        self.price = float(price) ## ! ##

##########################################################

print(data)

##########################################################

#fruits = set()

#for i in range(len(data)):
#    fruits.add(data[i]["fruit"])

#for fruit in fruits:
#    piece = 0
#    for i in range(len(data)):
#        if data[i]["fruit"] == fruit:
#            piece += 1
#    print(f"\t{fruit}: {piece} ")


# vowels list
#py_list = ['e', 'a', 'u', 'o', 'i']
#print(sorted(py_list))

# string
#py_string = 'Python'
#print(sorted(py_string))

# vowels tuple
#py_tuple = ('e', 'a', 'u', 'o', 'i')
#print(sorted(py_tuple))

#def leap_year(number):
    # = int(number)

#    if (number % 4 == 0 and number % 100 != 0 or number % 400 == 0):
#        return True
#    else:
#        return False


#for i in range(1900, 2000):
#    if leap_year(i) == True:
#        print(i)


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM