elkshadow5
elkshadow5

Reputation: 459

Reading and writing to text file adds invalid characters

Working on reading from, parsing data, and then overwriting new data to a text file. My problem is, writing to the file is adding invalid characters to the beginning before adding what I want it to. The error I get is:

ValueError: could not convert string to float: '\x00\x0045.5'

45.5, 5.0 is the data I am trying to write to the file and each \x00 represents an invalid character added during the writing to the file process. Normally there's like 10-15 added each iteration. I can manually go into the text file and delete them, but what's the fun in that?

This is my code, and the try/except is what I added to try to fix the problem-

def __init__(self, power):
    self.name = "Dr. Strange"
    self.CloakOfLevitation = "I like Dr. Strange"
    self.EyeOfAgamotto = InfinityStones.TimeStone(5000 + power, self.name)
    self.win = False
    self.length = randint(2, 100)

    stats = open("Stats.txt", 'r+', encoding = 'utf-8')
    data = stats.read()

    try:
        avg, tries = data.split(sep = ',')
        avg = float(avg)
        tries = float(tries)
    except ValueError:
        stats.truncate(0)
        stats.write(data[1:])
        sleep(5)
        stats.close()
        self.__init__(power)

    self.new_avg = avg + (self.length - avg) / tries
    stats.truncate(0)
    stats.write(str(self.new_avg) + ',' + str((tries + 1)))
    stats.close()

The majority of this code involves recursion, self.length determines how long the recursion will last, power is just a number and isn't important for this part. sleep(5) is in there so I can stop the program while it's running before it blows up my computer. Each time it writes data to the file, it adds invalid characters (represented as \x00 in the error output). avg is supposed to be the average number of 'deaths' before the recursion is done, and tries is the number of times the program has been run.

The idea of the try/except block is to attempt to convert the data in the file to integers so math can be done with them, and if it can't turn it into a character, attempt to drop the first character in the text file (supposedly an invalid character) and then try again (rerun __init__). Currently it just kinda blows up.

I saw stuff about encoding, and tried that, but it didn't change anything. Invalid characters are still being added. I have truncate(0) there to wipe the file so that I'm overwriting the file instead of appending data.

Upvotes: 1

Views: 1334

Answers (1)

davidejones
davidejones

Reputation: 1949

I think you need to step back in the file anytime you do a truncate. So where you do this stats.truncate(0) add stats.seek(0) after

Upvotes: 3

Related Questions