I need help with a problem concerning the code below.
with open ("Premier_League.txt", "r+") as f:
i= int(input("Please put in your result! \n"))
data = f.readlines()
print(data)
data[i] = int(data[i])+1
f.seek(0) # <-- rewind to the beginning
f.writelines(str(data))
f.truncate() # <-- cut any leftovers from the old version
print(data)
data[i] = str(data)
For example if the file Premier_League.txt contains:
1
2
3
and as I run the program and choose i as 0
that gives me:
[2, '2\n', '3']
and saves it to the already existing file (and deletes the old content) But after that I cannot run the program again and it gives me this:
ValueError: invalid literal for int() with base 10: "[2, '2\\n', '3']"
My question is: How do I make the new file content suitable to go into the program again?
3 Answers 3
I recommend this approach:
with open('Premier_League.txt', 'r+') as f:
data = [int(line.strip()) for line in f.readlines()] # [1, 2, 3]
f.seek(0)
i = int(input("Please put in your result! \n"))
data[i] += 1 # e.g. if i = 1, data now [1, 3, 3]
for line in data:
f.write(str(line) + "\n")
f.truncate()
4 Comments
Premier_League.txt file... if it contains '2\\n' as in your question, you'll receive that error.f readlines() read all content in a list as a string,if you want write back those contents as int
data=[]
with open ("Premier_League.txt", "r+") as f:
i= int(input("Please put in your result! \n"))
data = f.readlines()
with open ("Premier_League.txt", "w") as f:
for j in data:
f.write(str(int(j)+1))
#or do this to make it more clean,these lines are comments
#j=int(j)+1
#f.write(str(j))
# <-- cut any leftovers from the old version
print(data)
Note that,once you open a file,if you don't close it,your written contents can be lost,whatever you want to do with data,your have to do it in the second writing method .Also notice the change from r to w in with open ("Premier_League.txt", "w") for writing
5 Comments
Following my solution:
with open ("Premier_League.txt", "r+") as f:
i= int(input("Please put in your result! \n"))
# here strip wrong chars from input
data = f.readlines()
print(data)
# here added the str(..) conversion
data[i] = str(int(data[i].strip())+1) + '\n'
f.seek(0) # <-- rewind to the beginning
# the str(data) is wrong, data is a list!
f.writelines(data)
# I don't think this is necessary
# f.truncate() # <-- cut any leftovers from the old version
print(data)
# i think this is not necessary
# data[i] = str(data)