Python columns excel csv

Asked

Viewed 931 times

2

I made this number generator that gets saved in a csv file that I open in excel, the combinations are generated in column A but n want it to appear in A. as I do for her to appear in column B and C?

generate in B, paste in C the same combinations of B

   import random

    c1 = (random.choice([9, 9]))
    c2 = (random.choice([1, 1]))
    c3 = (random.choice([9, 9, 9]))
    lista = []

    print ('---criado por xxx---')

    rc = int (input('Quantas combinacoes?: '))

    def gerar_randomico():
        return random.choice([2, 3, 4, 5, 6, 7, 8, 9])

    def gerar_randomicus():
        return random.choice([6, 7, 8, 9])

    for i in range(rc):
        lista1 = ('{}{}{}{}{}{}{}{}{}{}{}\n'.format(c1, c2, c3, gerar_randomicus(), gerar_randomico(), gerar_randomico(),
                                                  gerar_randomico(), gerar_randomico(), gerar_randomico(),
                                                  gerar_randomico(), gerar_randomico()))

        with open('arquivo.csv','a') as arquivo:
            arquivo.write(str(lista1))
            lista_guardar = lista.append(arquivo)
            print(lista_guardar)

inserir a descrição da imagem aqui

4 answers

1

When generating a multicolumn file for Excel in en, the delimiter should be changed from , for ;.

For when generating a list with the following data on each line:

("", número_aleatório, número_aleatório)

Python generates a csv file with the tab ,, it is possible to open in Google Spreadsheet or other type of csv reader. But not in Excel in some Latin languages, which use ;.

Code

import random
import csv

c1 = (random.choice([9, 9]))
c2 = (random.choice([1, 1]))
c3 = (random.choice([9, 9, 9]))
lista = []

print('---criado por xxx---')

rc = int(input('Quantas combinacoes?: '))


def gerar_randomico():
    return random.choice([2, 3, 4, 5, 6, 7, 8, 9])


def gerar_randomicus():
    return random.choice([6, 7, 8, 9])


for i in range(rc):
    lista1 = ('{}{}{}{}{}{}{}{}{}{}{}'.format(c1, c2, c3, gerar_randomicus(), gerar_randomico(), gerar_randomico(),
                                                gerar_randomico(), gerar_randomico(), gerar_randomico(),
                                                gerar_randomico(), gerar_randomico()))
    lista.append(("", str(lista1), str(lista1)))


with open('arquivo.csv', 'w') as f:
    w = csv.writer(f, delimiter=";", dialect="excel", lineterminator = '\n')
    w.writerows(lista)

print(lista)

Upshot

The result for 3 combinations is as follows::

|   | A |      B      |      C      |
|---|---|-------------|-------------|
| 1 |   | 91962482524 | 91962482524 |
| 2 |   | 91962546353 | 91962546353 |
| 3 |   | 91977396769 | 91977396769 |

or the print of the list variable in Python: [('', '91962482524', '91962482524'), ('', '91962546353', '91962546353'), ('', '91977396769', '91977396769')]

0

Using the library pandas that helps greatly in the work of tabular structures you can simply add an empty column and then save the file in the extension you want.

import pandas as pd
import numpy as np
import random

c1 = (random.choice([9, 9]))
c2 = (random.choice([1, 1]))
c3 = (random.choice([9, 9, 9]))
lista = []

print ('---criado por xxx---')

rc = int(input('Quantas combinacoes?: '))

def gerar_randomico():
    return random.choice([2, 3, 4, 5, 6, 7, 8, 9])

def gerar_randomicus():
    return random.choice([6, 7, 8, 9])

df = pd.DataFrame()

df = pd.concat([pd.DataFrame([('{}{}{}{}{}{}{}{}{}{}{}'.format(c1, c2, c3, gerar_randomicus(), gerar_randomico(), gerar_randomico(), gerar_randomico(), gerar_randomico(), gerar_randomico(), gerar_randomico(), gerar_randomico()))], columns=['B']) for i in range(rc)], ignore_index=True)

df['C'] = df['B']

df.insert(0, 'A', np.nan)

df.to_csv('arquivo.csv', sep=",", header=None, index=None)

df = pd.DataFrame() creates a data structure called Dataframe initially empty

df = pd.concat() is a method that comes in to simplify the lista.append() that you had done. With it, you can concatenate native and performative form the desired data, still based on for i in range(rc). The values created in the loop will be added to the column B

df['C'] = df['B'] creates a column called C with the same values as in the column B

df.insert(0, 'A', np.nan) creates a column called A with null values (voids)

df.to_csv('arquivo.csv', sep=",", header=None, index=None) realizes the creation of the file . csv according to the parameters passed. 'arquivo.csv' is the file name, sep="," is the delimiter (as CSV means Comma Separated Values, the delimiter is the comma) and finally, header=None and index=None says that the file should be generated without the index column and without the header row.

I know your question wasn’t directly about Pandas, but I’m sure this tool will help a lot in your solution and in other similar genre.

Example working here

0

CSV (comma separated value) is a file where commas (,) delimit the columns. If Voce wants to create a file with the first blank column, Voce should put a comma in the first char of the string that will be saved. Something like:

lista1 = (',{}{}{}{}{}{}{}{}{}{}{}\n'.format(c1, c2, c3, gerar_randomicus(), gerar_randomico(), gerar_randomico(),
                                              gerar_randomico(), gerar_randomico(), gerar_randomico(),
                                              gerar_randomico(), gerar_randomico()))
  • n worked, this added a "0," in front of each number started with 91

0

Here it worked that way. Would that be?

import random

c1 = (random.choice([9, 9]))
c2 = (random.choice([1, 1]))
c3 = (random.choice([9, 9, 9]))
lista = []

print ('---criado por xxx---')

rc = int (input('Quantas combinacoes?: '))

def gerar_randomico():
    return random.choice([2, 3, 4, 5, 6, 7, 8, 9])

def gerar_randomicus():
    return random.choice([6, 7, 8, 9])

for i in range(rc):
    # AQUI VOCÊ APENAS GERA O NÚMERO (SEM O \n NO FINAL)
    lista1 = ('{}{}{}{}{}{}{}{}{}{}{}'.format(c1, c2, c3, gerar_randomicus(), gerar_randomico(), gerar_randomico(),
                                                  gerar_randomico(), gerar_randomico(), gerar_randomico(),
                                                  gerar_randomico(), gerar_randomico()))

    with open('arquivo.csv','a') as arquivo:
        # NA HORA DE ESCREVER NO ARQUIVO, VOCÊ COMEÇA COM ";" 
        # PARA DEIXAR A PRIMEIRA COLUNA LIVRE
        arquivo.write(';'+lista1+';'+lista1+'\n')
        lista_guardar = lista.append(arquivo)
        print(lista_guardar)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.