'how to create a program that writes a print("hello world"), in the main file where the original program was written? IN PYTHON
how to create a program that writes a print("hello world"), in the MAIN file where the original program was written? IN PYTHON
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.
Solution 1:[1]
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
Solution 2:[2]
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()
Solution 3:[3]
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")')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | djsokol |
Solution 2 | |
Solution 3 | Viettel Solutions |