0

Just wondering if there's a way to use a while loop for file appending; I'm attempting to use a small data file that's just 4 numbers to write to itself the same file a specific number of times. In my test case I just want to do it twice.

My code:

with open('data.txt', "a+") as file:
    i = 0
    while i<3:
        file.seek(0)
        data = file.read()
        file.write("\n")
        file.write(data)
        file.seek(0)
        i += 1
    

my data:

1.2, 2.5,
3.7, 3.9

Basically, I want to be able to iterate from 0,1,2 stop at 3 for i, and while this is occurring I am appending the data to itself so my end result should look like this:

1.2, 2.5,
3.7, 3.9
1.2, 2.5,
3.7, 3.9
1.2, 2.5,
3.7, 3.9
Benjamin Diaz
  • 141
  • 1
  • 10
  • 1
    Read the file content once, append it twice. Currently you are re-reading the file content during each iteration. – Mike Scotty Dec 08 '21 at 22:06
  • I would create a temporary file to write to and when finished move the temporary file to the existing location. – flakes Dec 08 '21 at 22:06
  • 2
    Hi, Benjamin! If this is not working, what is the problem you are facing? I don't see an error in your text. Did the file not change? – George Dec 08 '21 at 22:08

1 Answers1

1

You need a couple of changes in your code to make it work,

with open('data.txt', "r+") as fname:
    i = 0
    data = fname.read()
    while i<2:
        fname.write(data)
        i += 1

You need the original data to be read only once if you want to repeat only that. Otherwise, you'd be appending the whole current file each time. Given that, you don't need to rewind the file using seek, you just need to change the reading mode from appending, to reading and appending. You can find the details in this post.

Also, to end with three copies in the file you need i<2 instead of i<3.

atru
  • 4,699
  • 2
  • 18
  • 19