-1

If I want to run a program that writes a print("hello world") in the code of my main file, where I wrote the original program, how would I do that in Python?

I thought something like:

 import main


 with open("main.py " , "a+") as file_object:
    
      file_object.seek(0)

      data = file_object.read(100)

      if len(data)>0:

            file_object.write("\n")

      file_object.write('print("hello world)')

but the console shows this:

ValueError: I/O operation on closed file.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    You are trying to do an operation on a closed file. Also the indentation of the code is wrong. Try changing the indentation of the code. Without so many line breaks. – Fernando Carraro Apr 25 '22 at 03:29

3 Answers3

4

From my understanding, you are trying to determine if a file has content and if it does include a new line, and then append the print statement.

You do not need to use seek you can just check the size of the file:

import os

if os.path.getsize(filename):
    # file isn't empty
else:
    # file is empty

You should also close the quotation marks in your print statement

djsokol
  • 41
  • 2
3

You can use __file__ which gives you the path of your file and then append your text to it.

path = __file__

f = open(path, "a")
f.write('\nprint("hello world")')
f.close()
Sumit
  • 48
  • 7
0

you wrong because Indent correctly, like this. You can modify like:

import main


with open("main.py" , "a+") as file_object:

    file_object.seek(0)
    data = file_object.read(100)
    if len(data)>0:
        file_object.write("\n")

    file_object.write('print("hello world")')

Viettel Solutions
  • 1,519
  • 11
  • 22