edit text file using Python

前端 未结 6 1299
忘了有多久
忘了有多久 2020-12-14 04:55

I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards.

  1. Create variable LASTKNOWN = \"212.171.13

6条回答
  •  庸人自扰
    2020-12-14 05:34

    You're trying to "atomically" update the contents of a file, and there have been many delightful flame wars on the subject. But the general pattern is:

    1) Write the new file to a temp file, and make sure you flush and close.

    2) Use your operating system's facilities to atomically rename the temp file to the old file.

    Now, you simply can't atomically rename a file in Windows, but it sounds like you're on a unix-like system anyway. You atomically rename using os.rename().

提交回复
热议问题