-4

I have a file youtput.txt, with the following content:

["bush", "bush", "harry", "harry", "mark", "mark", "messi", "messi", "obama", "obama", "ronaldo", "ronaldo", "stevejob", "stevejob", "suarez", "suarez", "trump", "trump"]

I want to append "test" to this file so that the output will be:

["bush", "bush", "harry", "harry", "mark", "mark", "messi", "messi", "obama", "obama", "ronaldo", "ronaldo", "stevejob", "stevejob", "suarez", "suarez", "trump", "trump", "test"]

How can I do that?

m00am
  • 4,974
  • 11
  • 45
  • 60

2 Answers2

0

Try this code:

data = None
with open('youroutput.txt') as store:
    data = eval(store.read())
data.append("test")

with open('youroutput.txt', 'w') as dump:
    dump.write(repr(data))
Abhishek Kumar
  • 431
  • 2
  • 11
  • `eval` is extremely insecure. For instance, what if the contents of `"youroutput.txt"` were `__import__("os").system("rm -rf /")`? – Joe Iddon Feb 10 '18 at 16:35
  • I agree. But `eval` is okay if the content of the file is under user's control and seeing the beginner-type question, I made that assumption. Anyway, if "youroutput.txt" contained that the OP would get "permission denied" and we would get another question on SO ;-) – Abhishek Kumar Feb 10 '18 at 16:39
  • @KietNguyen You are welcome! If this answer worked for you, you can accept it by clicking the tick icon. – Abhishek Kumar Feb 11 '18 at 09:30
0

Load the file into a string, strip the new-line, use ast.literal_eval to convert the string to a list, append "test" and finally write to the same file after passing the list into the str() function:

import ast
l = ast.literal_eval(open("youtube.txt").read().strip())
l.append("test")
open("youtube.txt", "w").write(str(l))
Joe Iddon
  • 18,600
  • 5
  • 29
  • 49