I want to insert some text after a tab character in a textfile. How can I do this in python?
I have tried using Python seek() function. But is does not seem to take '\t'
(for tab) as an argument.
Thanks.
I want to insert some text after a tab character in a textfile. How can I do this in python?
I have tried using Python seek() function. But is does not seem to take '\t'
(for tab) as an argument.
Thanks.
You can't use seek for that. It is used to position the file cursor at a certain position in a file. (I.e. set the cursor to a position as a count of characters).
If you really want to insert you have to rewrite everything behind the cursor position anyway, otherwise your insertion overwrites bits of the file.
One way to do this is this:
fd = open(filename, "r+")
text = fd.read()
text = text.replace("\t", "\t" + "Inserted text", 1)
fd.seek(0)
fd.write(text)
fd.close()
text_to_insert = 'some text'
with open('test.txt', 'r+') as f:
text = f.read()
tab_position = text.find('\t')
head, tail = text[:tab_position+1], text[tab_position+1:]
f.seek(0)
f.write(head + text_to_insert + tail)
As already mentioned, you'll need to re-write the file for that insertion. A possible solution would be to save the file into a string, replace the first occurrence of a tab, and write the derived string into a new file
file_string = open(somefile).read()
modified_string = file_string.replace("\t", "\t" + "what you want to insert", 1)
with open(new_file, "w") as mod_file:
mod_file.write(modified_string)
Note that the third argument of the replace
method will only replace the first tab it will find in the string.
>>> for lines in textfile:
... lines = lines.split("\t")
... lines[1] = "This is your inserted string after first tab"