3

I am trying to make a program that continuously asks for a string and outputs that to the .txt file. It works fine without the while loop so I am not really sure whats going wrong here.

infile = open('hardlopers.txt', 'a+')
i = 0
while i < 1:
    naam = input('geef je naam:')
    infile.write(naam)
  • It is an infinite loop since you don't change `i`, which I guess is what you want. When are you checking the file? It could be that if you check the file before closing the program then the buffer will not be flushed so another program will not see the data. Try `infield.flush()` after the write. – cdarke Oct 06 '18 at 13:17

3 Answers3

5

Your program will run forever. The file you're writing to will not "save" (write to the actual file) until you close it (or explicitly tell it to, by using infile.flush()). Without the loop, the program terminates, which means that the file is closed and your changes are saved.

The flush() method does not always necessarily save the file. In that case, you can use os.fsync(infile.fileno()).

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
3

The content of a file is not written immediately to your harddisk. The content is stored in the files internal buffer and eventually given to your operating system wich in turn decides when to acctually persist your data on your haddrive.

More on file flushing (aka emptying the buffer to your disk): How often does python flush to a file?

It is better to use the with open(name, mode) as filehandle: paradigm when writing.

Try:

with open('hardlopers.txt', 'a+') as infile:
    while True:
        naam = input('geef je naam:')
        if naam:
            infile.write(naam)
        else:
            break

# now its written - with open autocloses on leaving the block

with open("hardlopers.txt","r") as r:
    t = r.read()
print("")
print(t)

Output:

geef je naam:a
geef je naam:b
geef je naam:c
geef je naam:d
geef je naam:
abced

See examples at: reading-and-writing-files

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1

You just need to break from the while loop so that contents are actually written to the file.

infile = open('hardlopers.txt', 'a+')
i = 0
while i < 1:
    naam = input('geef je naam:')
    if naam == 'q':
        i = 1 # break from the loop
    else:
        infile.write(naam)
jar
  • 2,646
  • 1
  • 22
  • 47