lista_arquivo=[]
with open("tabela1.csv", mode="r", encoding="utf-8") as o_arquivo:
for linha in o_arquivo:
lista_arquivo.append(linha.rstrip())
lista_arquivo
['0.0,8.0', '1.0,4.0', '3.2,4.3', '7.1,6.0', '5.7,3.0']
Neste primeiro passo construimos uma lista com as linhas do arquivo de texto. Precisamos transformar cada item da lista num ponto
[(float(p.split(',')[0]),float(p.split(',')[1])) for p in lista_arquivo]
[(0.0, 8.0), (1.0, 4.0), (3.2, 4.3), (7.1, 6.0), (5.7, 3.0)]
# podemos definir uma função para ler a tabela:
def LeiaTabela(csv_file):
''' retorna uma tabela a partir do arquivo csv_file '''
tabela=[]
with open(csv_file, mode='r',encoding='utf-8') as the_file:
for each_line in the_file:
tabela.append((float(each_line.rstrip().split(',')[0]),float(each_line.rstrip().split(',')[1])))
return tabela
# primeiro um teste
tabela1 = LeiaTabela('tabela1.csv')
tabela1
[(0.0, 8.0), (1.0, 4.0), (3.2, 4.3), (7.1, 6.0), (5.7, 3.0)]
Agora temos uma tabela de dados na variável tabela2
, e queremos guardar esta tabela num arquivo tabela2.csv
tabela1.append((6.0,2.6))
tabela1
[(0.0, 8.0), (1.0, 4.0), (3.2, 4.3), (7.1, 6.0), (5.7, 3.0), (6.0, 2.6)]
tabela2=tabela1
tabela2
[(0.0, 8.0), (1.0, 4.0), (3.2, 4.3), (7.1, 6.0), (5.7, 3.0), (6.0, 2.6)]
print(tabela2)
[(0.0, 8.0), (1.0, 4.0), (3.2, 4.3), (7.1, 6.0), (5.7, 3.0), (6.0, 2.6)]
texto=""
for point in tabela2:
texto = texto+str(point[0])+","+str(point[1])+"\n"
with open('tabela2.csv', mode="w", encoding='utf-8') as the_file:
the_file.write(texto)