简体   繁体   中英

Python Download Files in Linux- How to Not Replace File with the Same Name?

I have created a python script that will download files from a site using selenium and Chrome browser in a Linux environment. Since I am running a few instances at once, I ran into the problem of losing old files. The old file is often replaced by the new one because they are downloaded at the exact same time.

In windows, the file will be kept as filename(1), filename(2)..and so on. But specifically in Linux that is not the case. How can I go around this problem? (Is there any way I can change the Chrome sitting to disable the replacing function?)

Note: I already have a working function that renames the downloaded file right after it's done downloading. However, sometimes two files will finish downloading at the same time and only one will stay.

def rename():
    try:
        old_file = os.path.join(str(dlPath), "ClientReport.xlsx")
        new_file = os.path.join(str(dlPath), "ClientReport" + str(int(time.time())) + str(float(random.randint(0,100) + random.randint(1,99))/100) +'.xlsx')
        os.rename(old_file, new_file)
    except:
        print('No download to rename')

Thank you so much for you help!

Check if the file exist first:

if not os.path.exists(path):
    # Your copying logic
else:
    print('file not copied because it was already there') # something like this.

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