JohnTit
JohnTit

Reputation: 79

Incorrectly adding a line to a txt file

For some reason, when writing a string to a file in "a" mode, the necessary (conditional) string is added 125 times. Although one entry is obviously enough for me. And if you start adding in the "w" mode, then, respectively, the loop will add only the last checked line to the file each time, while clearing the previous one. How can I fix the addition via "a" mode?

workbook = open('base.txt')
print('Starting...')

count = 0
for line in workbook:
    number = (str(line)[0:11])


    with open(r"base.txt", "r") as file:
        lines = file.readlines()
    del lines[0]
    with open(r"base.txt", "w") as file:
        file.writelines(lines)

    for x in range(img.size[0]):
        for y in range(img.size[1]):
            pix = rgb.getpixel((x, y))
        if pix in color:

           with open('checkbase.txt', 'a') as filehandle:
                filehandle.write(line) #125 times add

    print(result)

Upvotes: 1

Views: 52

Answers (1)

Alexey
Alexey

Reputation: 178

You added your file appending operation in 'for' cycle. Your code should look something like this

for x in range(img.size[0]):
    for y in range(img.size[1]):
        pix = rgb.getpixel((x, y))
    if pix in color:
        result = '{cyan}YEAH{endcolor}'.format(cyan='\033[96m', endcolor='\033[0m')

with open('checkbase.txt', 'a') as filehandle:
    filehandle.write(line)  # appending file should now happen only once for every line    

When using 'w' mode for opening files, it overrides file content every time you open file, so you had only one record because it not only created, but also deleted 124 old records

Upvotes: 3

Related Questions