Python – Script para salvar conteúdo de um vetor em uma coluna de um arquivo texto

Escrevi esta função a partir da necessidade de processar uma grande quantidade de dados e precisar salvar uma tabela de dados no formato “tidy”(Uma maneira de organizar dados provenientes de diferentes observações de variáveis. É a representação tipicamente utilizada, por exemplo, pelo “R“).

Esta função simplesmente salva os elementos de um array como uma coluna num arquivo texto.

A função recebe como parâmetros:

  • o nome de um arquivo;
  • um array que será transformado em um vetor caso não tenha uma única dimensão;
  • uma string separadora a ser utilizada antes da gravação da coluna no arquivo fornecido.
#========================================================================
#                       addcoltofile
# Created on: 11/01/2012
# Author: xaoquadrado
# Purpose: Reads the elements of an array and save them as column in the
# provided file.
#
# filename -> the array will be added as a column to this file
# a -> array (will be transformed on a 1d array)
# sep -> separator string
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    See a copy of GNU General Public License at <http://www.gnu.org/licenses/>.
#========================================================================
def addcoltofile(filename,a,sep):
    a=np.ravel(np.asarray(a))
    s=sep
    try:
        f=open(filename,'r+')
    except IOError:
        s=""
        try:
            f=open(filename,'w+r+')
        except IOError:
            print "IOError."
            #return
    line=f.readline()
    if line=="":
        # File is empty
        for i in range(len(a)):
            f.write(str(a[i])+'\n')
    else:
        EOF=False
        pointer_to_write=0
        pointer_to_read=f.tell()
        new_line=line.rstrip('\n')+sep+str(a[0])+'\n'
        #print 'new_line= '+new_line
        invasion=len(new_line)-len(line)
        #print 'size of invasion='+str(invasion)
        #print 'pointer_to_write='+str(pointer_to_write)
        #print 'pointer_to_read='+str(pointer_to_read)
        buf=""
        for i in range(1,len(a)+1):
            #print EOF
            if EOF==False:
                aux=f.read(invasion)
                buf=buf+aux
                #print "Invasion read: "+str(aux)

            aux=""                        
            while (aux.find('\n')==-1) and (EOF==False):
                aux=f.read(1)
                buf=buf+aux
                #print 'updated buffer= \n'+buf
                if aux=="":
                    # Reached EOF
                    EOF=True
                    #print 'EOF'
                    break

            pointer_to_read=f.tell()

            f.seek(pointer_to_write)
            f.write(new_line)
            pointer_to_write=f.tell()
            f.seek(pointer_to_read)
            #print 'pointer_to_read='+str(pointer_to_read)
            #print 'pointer_to_write='+str(pointer_to_write)
            if i<(len(a)):
                x=buf.find('\n')
                line=buf[0:x+1]
                #print 'line= '+line
                new_line=line.rstrip('\n')+sep+str(a[i])+'\n'
                #print 'new_line= '+new_line
                invasion=len(new_line)
                #print 'size of invasion='+str(invasion)
                buf=buf[x+1::]
                #print 'buffer without line= \n'+buf
            else:
                break

        f.seek(pointer_to_write)          
        if f.readline()!="":
            print "Attention!The provided array has less elements than\n"
            print "the number of lines in the file."
        f.close()
        return

Uma ideia sobre “Python – Script para salvar conteúdo de um vetor em uma coluna de um arquivo texto

Deixe seu comentário