Reputation: 83
I'm still learning Python and decided to combine two different elements to understand loops and files better. I made a simple for loop that takes multiple inputs from the user and writes it into a file. I read and watch some tutorials on how to work with for loop and files. What I wanted to do is every time the user writes a line of string a number will be written at the beginning stating the position.
So, if I only write one line then the for loop will also write the number "1" at the beginning. If I write two lines of strings then it will be
The problem I'm having with this is that this method only works if I keep writing different lines of string in that debugging only.
If I stop writing and decide to start the loop again to write a new line then it start with number "1" again. Any idea how can I fix this and why is it happening?
Upvotes: 0
Views: 417
Reputation: 1302
Your code has several problems. So I recreated your code.
try:
with open("file.txt", "r") as l:
line = int(l.readlines()[-1][0]) + 1
except FileNotFoundError:
line = 1
This tries to read the file and get the last number if it doesn't exist it use 1.
with open("file.txt", "a") as f:
try:
while True:
f.write(f'{line} {input()} \n')
line += 1
except KeyboardInterrupt:
print('Quiting...')
This is same as your code but I add a way to exit(ctrl+c) without giving an error message.
So the final code will be like this:
try:
with open("file.txt", "r") as l:
line = int(l.readlines()[-1][0]) + 1
except FileNotFoundError:
line = 1
with open("file.txt", "a") as f:
try:
while True:
f.write(f'{line} {input()} \n')
line += 1
except KeyboardInterrupt:
print('Quiting...')
Upvotes: 1
Reputation: 70
The way to do that would be to read the file, then find the most recent line, and get that number.
You would then add 1 to it, and keep going from there
P.S. regex will help
Upvotes: 1