1

I got a .txt file with this list structure:

["saelyth", "somehting here", "Not needed", "2013-08-24 14:14:47"]
["anothername", "whatever 1", "Not needed neither", "2013-08-24 15:12:26"]
["athirdone", "just an example", "of the list structure", "2013-08-24 15:12:51"]

And I need to replace the second value of a specific list only if the value 1 is found in a file. The code I'm trying is this one, but so far that one is just appending data to the file instead of replacing it.

  horaactual = datetime.datetime.now()
  filename = "datosdeusuario.txt"
  leyendo = open(filename, 'r+')
  buffer = leyendo.read()
  leyendo.close()
  fechitaguardaips = str(horaactual)[:19]
  escribiendo = open(filename, 'r+')
  for line in escribiendo:
    retrieved = json.loads(line)
    if retrieved[0] == user.name:
      retrieveddata1 = "prueba"
      mythirdvalue = "not important"
      escribiendo.write(json.dumps([user.name, retrieveddata1, mythirdvalue, fechitaguardaips])+"\n")
      break
  escribiendo.close()

I guess the fail is in the line escribiendo.write. However, I've been googling for two hours and I did get this far, but I don't find a specific call to Replace data instead of writing or appending. How can I fix this problem?

This is what happens and shouldn't :(

["saelyth", "prueba", "", "2013-08-27 13:25:14"]
["saelyth", "prueba", "", "2013-08-27 13:25:32"]
["saelyth", "prueba", "", "2013-08-27 13:26:01"]

I also got troubles understanding what a Break does as I'd like to stop infinite loops from my code (it happened to me yesterday in a different section of the program, but I was also using "For line in X" in JSON Python).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Saelyth
  • 1,694
  • 2
  • 25
  • 42

2 Answers2

0

Here is an example which you could tweak to your needs:

from contextlib import nested

filename = 'datosdeusuario.txt'
with nested( open(filename,'r'),open(filename,'w') ) as f1,f2:
    for line in f1:
        f2.write(line.replace('foo','bar'))

This would replace every instance of the substring foo by bar in your file, even though it does open twice the file.

Mathieu Marques
  • 1,678
  • 15
  • 33
  • I'm doing something wrong, so far i'm getting import errors like " from contextlib import nested ImportError: cannot import name nested" but besides that, i just tried the line.replace feature (didn't know it exists) and it still adds a new line to the text instead of replacing the old one in the file, so i get 2 user.names with different values, wich should happen :( -- From the documantation -- str.replace(old, new[, count]) Returns a "copy" of the string... shouldn't be a copy but to edit the actual line :( – Saelyth Aug 27 '13 at 13:24
  • I believe `contextlib` is for Python 2.x only. Also, I think you are mixing up lines and strings. – Mathieu Marques Aug 27 '13 at 16:37
0

My approach is like this (based on an answer to Stack Overflow question Loading and parsing a JSON file in Python):

import json

data = []
with open('text.json', 'r+') as f:
    for line in f:
        data_line = json.loads(line)
        if data_line[0] == 'saelyth' and '1' in data_line[1]:
            data_line[1] = 'new value'
        data.append(data_line)
    f.seek(0)
    f.writelines(["%s\n" % json.dumps(i) for i in data])
    f.truncate()

Please correct me if I got your question the wrong way.

About your question with break, check Python break, continue and pass Statements.

Community
  • 1
  • 1
MGP
  • 2,981
  • 35
  • 34
  • ¡Yeah great!, that's exactly the code that i needed, it works perfect. I edited what i needed to make it works, but... i don't really understand how it works. For example, why the data value is just [] and nothing is inside? Also why to use the truncate command? – Saelyth Aug 27 '13 at 17:38
  • @Saelyth data is an empty list I used to put the new values, then seek(0) to place the cursor at the beginning of file and truncate to correct the file size, since it may had leftovers from previous data. http://www.tutorialspoint.com/python/file_truncate.htm – MGP Aug 27 '13 at 17:58
  • @Saelyth the beauty of Python is in the idioms, you might want to read a complete tutorial to really get it. http://www.diveintopython.net/ or http://www.diveintopython3.net/ – MGP Aug 27 '13 at 18:02
  • Yeah i can see that now, it's very tricky. Gracias por la ayuda. – Saelyth Aug 27 '13 at 20:09
  • Nevertheless this leads to a new problem: http://stackoverflow.com/questions/18474673/python-how-to-change-the-value-of-a-variable-on-the-fly – Saelyth Aug 27 '13 at 20:20
  • Check this, [StackOverflow in Spanish](http://area51.stackexchange.com/proposals/42810/stack-overflow-in-spanish?referrer=xLx9d-m4m0M9zlsUrCq6xg2) Un placer ayudar. ;) – MGP Aug 27 '13 at 20:26
  • Uhm interesante, me apuntaré. – Saelyth Aug 27 '13 at 20:30