2

I am a newbie python developer and I have a question. I have a python script check if updates are available on an external webpage but I got stuck while trying to get it to override old file with new one. What the code does below is get new.py and open it as a txt file. It then searches for __VERSION__. My code for searching for new version is below. How would I replace current.py with new.py?

__VERSION__ = '1.0'
#Get new version
new_version = ''
with open('new.py') as newfile:
    for line in newfile:
        line = line.strip()
        if '__VERSION__' in line:
            _, new_version = line.split('=', maxsplit=1)
            new_version = new_version.strip()
            break

Thanks @user:6530979 Can anyone help me understand what to do after this? EDIT: The goal is for current.py to override its self with new.py’s code Any help will be appreciated!!

  • 1
    Is the code sample you include above a part of `current.py`? In other words, is the goal to have `current.py` overwrite itself? – Michael Noguera May 22 '20 at 00:49
  • Yes this is the goal. –  May 22 '20 at 00:54
  • what's wrong with checking each line if ____VERSION____ is in it and then replace it, and write that new line to the file? basically first read the entire file and save it in a list with readlines. then check each line in the file by iterating over the list and replace ____VERSION____ with what you want? and then after that just write the list to the file – DarkLeader May 22 '20 at 01:05
  • Can you provide a code example so I can fully understand what you mean because I am not sure what you are getting at? –  May 22 '20 at 01:18

2 Answers2

1

Overall, these solutions are hacky at best-- no guarantees.

You SHOULD look into package management/version control, because the systems already developed to do this are likely to be much more reliable.

BUT, you might be able to use os.rename. I'm not sure if this is a good solution, or how safe it is, but it worked in my quick trial.

''' current.py (V1) '''
import os

os.rename("current.py", "old.py")
os.rename("new.py", "current.py")

In this case, current.py (V1) is the file run by the user. After execution, you are left with old.py and current.py (V2).

Two things to note:

  1. You won't have line-by-line control via this method.
  2. You might want to make this program call another (like V1 calling V2 and then exiting), using strategies such as these.
Michael Noguera
  • 401
  • 4
  • 14
1
# what you want to replace '__VERSION__' with
replace = 'what ever you want'
new_lines = []
with open('new.py',"r") as newfile:
    lines = newfile.readlines()
    for line in lines:
        new_lines.append(line.replace("__VERSION__", replace))


with open('new.py',"w") as newfile2:
    full_file_text = "".join(new_lines)
    newfile2.write(full_file_text)

is this what you wanted? to replace some text in a specific line?

DarkLeader
  • 589
  • 7
  • 17