0

I am trying to create a .py file from a .py file and then run the newly created .py file. The problem is, after creating the file from my original file, when I open the new file, there is literally nothing in the file. Here is my code:

bfile = open("browsertask.py", "w+")
print('success')
bfile.write("from selenium import webdriver")
print('success2')
bfile.write("driver.get('" + link + "')")
print('success3')
os.system('python browsertask.py')

(the variable link was defined before in the program)

The code runs without raising any errors. When I check the newly created file to see if the text was written to the file, there is nothing in the file. I researched this and I do not think I am doing anything incorrect.

Does anyone know what I am doing wrong here?

EDIT: Thanks to the users in the comments telling me to close the file before running, this actually fixed the problem!

EDIT: I don't know how to mark my question as answered, I tried answering it myself and accepting that answer but I have to wait two days.

martineau
  • 119,623
  • 25
  • 170
  • 301
Epacity
  • 97
  • 12
  • 4
    You should `close` the file before reading or executing. – Michael Butscher Nov 19 '18 at 01:40
  • 2
    If you use `with open("browsertask.py", "w+") as bfile:` you can get the file [to close automatically](https://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file) if you put your `write()` calls in a block. – Ken Y-N Nov 19 '18 at 01:44
  • 2
    You probably will want CR/LF at the end of you lines. so you might want to add '\n' to the strings you are writing. – Red Cricket Nov 19 '18 at 01:46
  • Why are you creating a new Python file? Python can do your task very simply without it. – Klaus D. Nov 19 '18 at 01:54

1 Answers1

0

Turns out all I needed to do was close the file I was making before running it and that worked perfectly, now the file actually saves what I write to it.

Epacity
  • 97
  • 12