0

I am trying to write a string Test string: Correct before the } in the input file, input.txt.

The input file looks like the following:

{
   File name: test.txt
   File contents : valid
   File type: txt
   Test string: Correct <- this is what i want to add here before the } at the end of the file
}

My code is below. I am not able to figure out how to add the test_string before the last } in the file. May someone please guide me?

test_string = "Test string: Correct"

with open(test.txt, "a") as file:
    file.write(test_string + "\n")
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Analia
  • 83
  • 1
  • 11
  • Files are streams – writing something before something else will overwrite the latter. Do you always want to write your text *before the last two bytes* which are always ``b"\n}"``, or do you want to write your text *before some content* which you do not know precisely (for example ``b" \n } "``)? – MisterMiyagi Feb 10 '21 at 19:00
  • https://stackoverflow.com/questions/37824439/writing-on-the-topmost-row-of-a-csv-file The answer here should put you on the right path. In short, you can't add to the middle of a file without also needing to re-write everything after that point. – coreyp_1 Feb 10 '21 at 19:05
  • @MisterMiyagi I want to write the text before some content which you do not know precisely (for example b" \n } ") – Analia Feb 10 '21 at 19:09
  • @coreyp_1 I am not able to follow it? May you help me? – Analia Feb 10 '21 at 19:11
  • If you do not know at least one particular condition when you want to add the new line, how can it be done? If you know at least one condition like 'last but one line', 'after first 5 lines', 'after I read File type: txt' then you can make use of that. Write a new file and at the end, use shutils to move the new file to overwrite the old file. – lllrnr101 Feb 10 '21 at 19:22
  • @lllrnr101 If I have to write it at the last but one line, how can I do that? – Analia Feb 10 '21 at 19:26
  • I would use `data=readlines()` and get all the data. Then write till data[:-1] and then write my new string and then data[-1]. Then use shutils to move this temp file to old file. – lllrnr101 Feb 10 '21 at 19:29

1 Answers1

2

You can try this:

with open("file.txt", 'r') as file:
    lines = file.readlines()

string = "\tTest string: Correct"
lines.insert(-2, string)

with open("file.txt", 'w') as file:
    file.writelines(lines)

As people said in the comments there is no way to insert something into the file without rewriting it. You can only read, write and append.

Also consider naming your output file something else, or making a back up of the original file. You do not want to lose the contents if something goes wrong during the write process (encoding issue for example).

sarartur
  • 1,178
  • 1
  • 4
  • 13