Home > Blockchain >  Open a file while using classes/modules
Open a file while using classes/modules

Time:02-06

I am trying to create a bank account program and I need to save a file with all the transactions that the user does. I'm trying to use classes and it's not working for me. someone can help or give a better solution?

class BankAccount():
def __init__(self, first_name, last_name, personal_number,currency, amount = 0):
    self.first_name = first_name
    self.last_name = last_name
    self.personal_number = personal_number
    self.currency = currency
    self.amount = amount
    self.the_file = open("{self.personal_number}.txt", "a")
    self.the_file.write("{self.first_name} {self.last_name} {self.personal_number}\n In the bank {self.amount} {self.currency}")
    print(self.the_file.readlines())


anton = BankAccount("anton", "james", "123456789", "$", 15)

enter image description here

CodePudding user response:

You can't read this file because you opened it on append mode. To read and append to the file you have to open it with the a mode.

myFile = open("myfile.txt", "a ")
myFile.seek(0)

print(myFile.read())

The myFile.seek(0) must be called because when opening with append mode the "file cursor" is automatically at the end

CodePudding user response:

You are opening the file in append mode, which means "write at the end of the file"). So reading is invalid. You should open the file in read&write mode for your code to work. which would be:

self.the_file = open(f"{self.personal_number}.txt", "w ") # "r " also works

Also mind you aren't using format string properly, make sure to have a f before the quotes.

This will solve your problem, however you will have bad time reading your data from those files. You should serialize your data (pickle, json, csv...).

  •  Tags:  
  • Related