-1

I want to apologize for sucking at coding before I begin.

So I store ONLY integers in the first line of a text file in python. And I want a function to add +1 to the integer in the text file.

def addone():
    with open("data/"+str(messager)+".txt", "r+") as f:
      dataint = f.readline()

This is my unfinished code of the function. Right now dataint = 1, but it's a string.

How do I make it so that it adds +1 to dataint and prints the value every time this function is called?

  • 1
    can you show an example of the text file? first of you say there are integers in the first line meaning there are multiple, also you say that it is in the first line which doesn't necessarily imply but suggest that you may have other data in other lines of the file and what do you mean by `printing` the value? do you want to simply `print` some value? – Matiiss Dec 04 '21 at 22:32
  • Does this answer your question? [How to read numbers from file in Python?](https://stackoverflow.com/questions/6583573/how-to-read-numbers-from-file-in-python) – Tomerikoo Dec 04 '21 at 22:40
  • I only store 1 line of data in the .txt file. Apologies if I couldn't make it obvious. And yes, I just mean that I want to ```print(dataint)``` :) sorry if my code is dumb, I'm just really new to coding :p I appreciate all the feedback! – Ege Gürsel Dec 04 '21 at 22:41

2 Answers2

1

If you have an integer in the first line, first column, you can use this method which will also keep any other data in the file (it is possible to also have the integer somewhere else but that either makes this method a bit more complicated or have to use a different method):

def add_one():
    with open('myfile.txt', 'r+') as file:
        integer = int(file.readline())
        print(integer)
        # sets the file pointer? at the first byte 
        # so that the write method will overwrite the first bytes of data
        file.seek(0)
        file.write(str(integer + 1))


add_one()
Matiiss
  • 5,970
  • 2
  • 12
  • 29
0
def addone():
    file = open("data/" + str(messager) + ".txt", "r")
    dataint = f.readline()
    dataint = int(dataint) + 1
    file.close()
    file = open("data/" + str(messager) + ".txt", "w")
    file.write(str(dataint))
    file.close()

This code will read the file, add 1, than will rewrite in the same file the new value

Alexandru DuDu
  • 998
  • 1
  • 7
  • 19