0

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.

user189942
  • 351
  • 1
  • 3
  • 12

4 Answers4

2

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()
ted
  • 4,791
  • 5
  • 38
  • 84
  • 1
    I think you wanted to do `txt.read()` instead of `txt.read` and `.replace("\t", "\t"+INSERTED_TEXT, 1)` instead of `.replace("\t", "\t", 1)` – Elisha May 19 '15 at 11:17
  • @Elisha: thanks for spotting this, and feel free to just correct obvious mistakes like this, after all this is why you can edit others posts (I believe). – ted May 19 '15 at 11:24
1
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)
BioGeek
  • 21,897
  • 23
  • 83
  • 145
1

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.

ODiogoSilva
  • 2,394
  • 1
  • 19
  • 20
0
>>> for lines in textfile:
...     lines = lines.split("\t")
...     lines[1] = "This is your inserted string after first tab"
jester112358
  • 465
  • 3
  • 17