简体   繁体   中英

How can I avoid overwriting a file which has all the print result in python

I'm running a Python script to run commands on switches. It's logging the switch running those commands and printing this output in a file.

Now I will make changes on my file and rerun it. Now the results that are generated will be saved in the same location as the previous file. I don't want to overwrite the previous file. Instead, I want to create another file and do a diff on both files. Also, the script should create another file if there is another file with the same name in the directory of the outputted file(s). I'm using Python 3.

import os

I'm assuming you're writing to the "current working directory." In this case I will be using os.getcwd() as the output location.

Anyway you can use os.listdir(os.getcwd()) to get the names of all of the files in the folder you're writing to. Then just iterate through like this:

filename = "75077597_"
suffix = ".txt" 
files = os.listdir() # if there's a specific path, add it as an argument
for number in range (40000): 
    if not (filename + str(number) + suffix) in files: 
        # write file using the filename: (filename + str(number) + suffix)
        break

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