-3

Im new to python and I need some help from you guys.

So this is my Code

Tk().withdraw() 
filename = askopenfilename(title='Choose a file', filetypes=[("Text Files", "*.txt")]) 

f = open(filename)


with open(filename,'r+',encoding="UTF-8") as file:
 file.write('test')
 file.write('\n')

file_contents = f.read() 

This is the Text File without using file.write

Im a big noob in python please help me.

And this is after using file.write

test
ig noob in python please help me.

My Goal is to append the Text to the top of the text file without replacing the contect underneath it.

GoekhanDev
  • 326
  • 2
  • 4
  • 20
  • Check out this answer, it might help: https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file – slaughter98 Dec 24 '19 at 17:50

2 Answers2

1

When you write to a file it always effectively overwrites the bytes inside the file stream. What you might want to do instead, is read the file first, and write the necessary parts, and then write your original contents back:

with open(filename,'r+',encoding="UTF-8") as file:
    data = file.read()
    file.write('test\n')
    file.write(data)

This should be all you need. Remove the f = open(filename) and file_contents = f.read() lines, because you are opening the same file twice.

r.ook
  • 13,466
  • 2
  • 22
  • 39
1

Just copy the content first and insert it in the beginning, like this:

with open(filename,'r+',encoding="UTF-8") as file:
 previous_content = file.read()
 file.write('test\n' + previous_content)
marcos
  • 4,473
  • 1
  • 10
  • 24