0

I am currently using this to try to extract text and strings etc in between quotes and load the text box with the extracted text/string. I am wondering if there is a way to write the text back inside of the text document to the exact position that it was originally in or write it back between the quotes I am extracting from now?

For example if I had a line like this in the text document:

Random Text Random Text "Hello world, this is text document file.txt" Random Text Random Text

How could I be able to extract what is inside the quotes and edit it in the text box and then write it back to where it came from?

This code works to do everything but write it back to the text document in between the quotes. I could not figure that part out. It writes to the text document just fine as is but it over-wrights the file in the current config. I have been looking into readlines, writelines and regex etc to solve this but I am stumped.

from Tkinter import *
import re

root = Tk()

with open('file.txt', 'r') as f:
    data = ''.join(f.readlines())
m = re.search('"([^"]*)"', data, re.S | re.M)

tBox = Text(root, height=2, width=50)
tBox.insert(END, m.group(1))
tBox.pack()

def retrieve_input():
    inputV = tBox.get("1.0", "end-1c")
    f = open('file.txt', 'w')
    f.write(inputV)
    f.close()

btn = Button(root, text="Go", command=lambda: retrieve_input())
btn.pack()

root.mainloop()
John
  • 1
  • 1
  • 2
    Don't try to do a partial modification of 'file.txt'. Just modify `data` and write the whole thing to 'file.txt'. – PM 2Ring May 31 '17 at 15:41
  • That's probably what I will end up doing. Was just hoping that I could figure something out to just write the strings etc on the fly. – John May 31 '17 at 15:53
  • It's _possible_ to perform modifications of a file contents, but it's messy, and easy to get wrong, since the new data has to be exactly the same size as the old data, unless you're modifying the data at the very end of the file. Unless the file is huge, it's simpler just to re-write the whole thing. – PM 2Ring May 31 '17 at 15:56
  • Yeah, that pretty much sums up what I have read about trying to do this, this morning. Thanks for the response. – John May 31 '17 at 16:01
  • If you're curious, [here](https://stackoverflow.com/a/40449253/4014959) is some code that performs in-place modification of a text file. – PM 2Ring May 31 '17 at 16:10
  • Cool, I'll mess around with it for a bit. – John May 31 '17 at 16:13

0 Answers0