简体   繁体   中英

Is it wise to remove files using os.rename() instead of os.remove() in Python?

I have a file named fin that I need to modify.

In Python I created a script that makes the modifications I need and then save it in new file named fout .

The older file is useless to me, so I use os.remove('fin') to remove it. However, the modified file should be named fin , so I use os.rename('fout','fin') .

I thought about a shortcut that is straight up using os.rename('fout','fin') , expecting it to delete fin since it's the same name, but I`m not sure if this is in fact deleting my older file or if it may cause some trouble if I do this several times (doing this task over a 1000 times).

My question is: is this the cleanest and fastest way to achieve this goal? In summary I just want to make corrections in the original file and overwriting it.

code:

import os

f = open('fin','w') 
f.write('apples apple apples\napple apples apple\napples apple apples') 
f.close()

with open('fin', 'rt') as fin:
   with open('fout', 'wt') as fout:
      for line in fin:
         fout.write(line.replace('apples', 'orange'))
os.rename('fout', 'fin')

Your pattern works on POSIX systems, but won't work on Windows. I'd recommend using os.replace which replaces existing files in an OS agnostic fashion. It requires Python 3.3 or higher, but then, new code should generally be targetting Python 3 anyway.

It's the preferred pattern because it guarantees atomicity; the fin file is always in a complete state, either before or after, with no risk of failures leading to it existing in a partial/corrupt state.

It doesn't seem from your example that you would have a reason to iterate through the file line by line. If that is the case this is a pretty simple solution.

f = open('fin','w').write('apples apple apples\napple apples apple\napples apple apples')

s = open('fin').read().replace('apples', 'oranges')
open('fin','w').write(s)

For the sake of cross compatibilty, I recommend you invert the with code. My suggestion code is

f = open('fin','w') 
f.write('apples apple apples\napple apples apple\napples apple apples') 
f.close()

with open('fout', 'wt') as fout:
    with open('fin', 'rt') as fin:
        for line in fin.readlines():
            fout.write(line.replace('apples', 'orange'))
    os.unlink('fin')
    os.rename('fout', 'fin')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM