0

So i have am trying to go through a text file, put it into a dictionary, and then check to see if a string is already in it. if it is, i want to change the "1" to a "2". Currently if the string is already in the text file, it will just make a new line but with a "2". is there a way to edit the text file so the number can stay in the same place but be replaced?

class Isduplicate:
dicto = {}

def read(self):
    f = open(r'C:\Users\jacka\OneDrive\Documents\outputs.txt', "r")

    for line in f:
        k, v = line.strip().split(':')
        self.dicto[k.strip()] = int(v.strip())

    return self.dicto

Is = Isduplicate()

while counter < 50:
   e = str(elem[counter].get_attribute("href"))
   e = e.replace("https://www.reddit.com/r/", "")
   e = e[:-1]

   if e in Is.read():
       Is.dicto[e] += 1
   else:
       Is.dicto[e] = 1

   text_file.write(e + ":" + str(Is.dicto[e]) + '\n')




   print(e)
   counter = counter +2
  • On the line with text_file.write, you have `+'\n'`, which adds a newline... – Rushabh Mehta Jul 30 '18 at 15:20
  • @RushabhMehta sorry maybe i didn't convey what i am asking well enough. i want to update a line that would already be in the dictionary when scanned in. i dont know how to go to the specific line and change the value. – jack arnold Jul 30 '18 at 15:23
  • Do you _just_ want to know how to modify a character inside an existing text file? – PM 2Ring Jul 30 '18 at 15:24
  • My old answer [here](https://stackoverflow.com/a/32098399/4014959) shows how to modify the contents of a text file. It uses Python 2, but it's easy to convert it to Python 3. Note that this is _not_ recommended. It's generally better to create a new copy of the file. And if you want to work on a binary file see [here](https://stackoverflow.com/a/33715812/4014959). – PM 2Ring Jul 30 '18 at 15:32
  • @PM2Ring yes, i just want to change the number in the dictionary – jack arnold Jul 30 '18 at 15:32
  • I don't understand why your program reads the same file `'C:\Users\jacka\OneDrive\Documents\outputs.txt'` over & over again. It would be more efficient to read it once, do all the searches & modifications you want, and then write the modified version when you've finished. – PM 2Ring Jul 30 '18 at 15:38

1 Answers1

0

You can not rewrite a particular byte in a file, you have to rewrite the file in a whole.

Probably reading the file into the list of strings, processing that list and writing it back to the file would solve your task.

  • You certainly _can_ rewrite a particular byte in a file, but it's generally not a good idea to do so: if you miscalculate, it's too easy to make a mess of the file. – PM 2Ring Jul 30 '18 at 15:52
  • You mean low-level HDD-access or are there any conventional ways? –  Jul 30 '18 at 16:01
  • 1
    There are conventional ways, using standard library functions. See my code that I linked in my 2nd comment on the question. – PM 2Ring Jul 30 '18 at 16:09