0
append 'int' in a .txt file
hey How do i append an int to a .txt file? i looked it up, but didn't find a solution. i want to make a .txt file that counts to infinity but i only can append string values. So i get this 1 11 111 1111 11111 instead of 1 2 3 any ideas? thanks
4 Answers
0
All files just store bytes and are content-agnostic. Generally when you view a file you interpret each byte as an ASCII character.
You can either append the integer as-is using fwrite and also build a program for reading the file, or convert your ints to strings before appending them.
0
Would be nice if you show how do you append the integer to a file. Do you read its contents first and? if so, you have to convert the read value to integer, then incease it, an then write back to the file.
0
# i found something that works but probably not a good way
counterFile = open("Counter file.txt", "w")
counterFile.close()
y = 0
while True:
y = str(y)
y = int(y)
y = y + 1
y = str(y)
time.sleep(1)
appendFile = open("Counter file.txt" ,"a")
appendFile.write(y)
appendFile.write("\n")
appendFile.close()
# this makes a .txt file and it counts to infinite 'till program is stopped
0
Jordi de Pelseneer
Do not convert y into str and back. If you set it to 0, you declare it as numeric. Just write it into the file. You do not need to open and close the file before the while loop.