Write multiple csv files in Python [closed]

-2

Hello! My question is this: I wrote a program that, with the information I enter, it will collect a number of links (this number varies) and will store them in a csv. Then it will open each of these links and collect some data, saving them in another csv. The problem is in this second part ...

When we use something like "csvFile = open ('File.csv', 'wt +')", it will create a file named File.csv. The issue is that my program will do this several times in a row, and if I keep the name the way it is it will not create a .csv file (as windows usually do with files of the same name), it will replace one file on top of the other. If the number of times my program runs was predefined, I could type opens as many times as needed, the problem is that it is not, it can run this 10 times, or 1000, etc ...

How can I make my program to create a csv with the collected data, and in the following link does it create a different csv, without replacing the previous one? File type 1.csv, 2.csv file, 3.csv file, etc. Is that possible?

Thank you in advance.

    
asked by anonymous 05.11.2018 / 11:50

1 answer

0

This function below finds a unique name for the file. It adds 001 , 002 etc until you find a number that does not yet exist.

def acha_proximo_nome(nome_arquivo):
    if not os.path.exists(nome_arquivo):
        return nome_arquivo
    base, extensao = os.path.splitext(nome_arquivo)
    numero = 1
    while True:
        nome_arquivo = '{}_{:03d}{}'.format(base, numero, extensao)
        if not os.path.exists(nome_arquivo): 
            return nome_arquivo
        numero += 1

How to use:

f = open(acha_proximo_nome('arquivo.csv'), 'w', newline='')
    
05.11.2018 / 18:04