python string manipulation

2

I'm having a problem with python \ b (backspace), instead of deleting the previous character, it generates a "•" as shown below:

Thefollowingisthelineofcodethatgeneratesthisreturn:

#-*-coding:utf-8-*-importpyodbcimportplatformimportjson#------------------------------------------------------#local_arq=open("C:\Zabbix\prm2.txt", 'r') #Caminho do arquivo cujo encontra-se aa instancias
leitura = local_arq.readlines() #leitura das linhas do arquivo
varhost = platform.node()
x = 0 #var usada para separar os dados recebidos do TXT && Alterar o valor do hostname 
y = 0 
with open("test3.txt","w") as arq:
    print('{"data": [')
    for li in leitura:
        count = li.split('--') #count = contador ele recebe os dados do TXT e separa eles onde tem o -
        count[x].replace(" ", "") #Remove todos os espaços

        for li2 in count:   
            hostname = varhost + '\' + count[x]
            con = pyodbc.connect("DRIVER={SQL Server};server="+hostname+";uid=sa;pwd=Ww1234567.")
            query = con.cursor()
            query.execute("SELECT name FROM SYSDATABASES")

            for row in query:    
                #print(row)
                print('{"{#INSTANCENAME}": "%s","{#DBNAME}": "%s"},' %(count[x], row[y]))
                lol = ('{"{#INSTANCENAME}": "%s","{#DBNAME}": "%s"},' %(count[x], row[y]))
            x = x + 1
            print(lol + '\b]}')
        y = y + 1

In this case, I'm using \ b to delete that comma.

Thank you in advance!

NOTE: Python 3.7 version

    
asked by anonymous 04.07.2018 / 22:30

2 answers

3
There is a concept error there - "\ b" is simply a control character, called "backspace", which has decimal code "8" - when printed on a terminal, the terminal protocol is causes the previous character to be deleted .

But for writing a file, "\ b" is a character like any other - in most text encodings - ASCII, Latin1 and UTF-8 inclusive, it will simply generate a byte with value "8" that goes stay in the file. Then, if the file is printed in a terminal, it will appear that the previous character has been deleted - instead of opening your file in a text editor, display its contents (command cat on Linux / Unix / OS X , or type in DOS / windows).

That is, what you need to do is not save the unwanted comma in the file to begin with. You have not put more parts of your program, so you can not say exactly where you can do this, but in general it will require you to have a "counter" vairável, and record the comma at the beginning of each item if that item < in> no is the first one.

Or, if you have the entire list of items when you are recording, the .join method of Python lists already puts the commas just as separators for the items. So let's assume you have everything you want to write to the file in a "values" list, you can do this:

arq.write("""{"chave":[%s]}""" % ", ".join(valores))

(Here I used the old % mode to interpolate strings to avoid having to escape the dictionary keys from outside, using .format or f-strings)

A better alternative, if you are creating a JSON file, is to let Python transform a "live" data structure consisting of diaries and lists into the JSON string.

import json
arq.write(json.dumps(meus_dados))

where "my_dates" is a dictionary, with the necessary lists and sub-dictionaries. Using the JSON encoder is much better than trying to generate the string manually, because it accounts for all other instances where JSON would give error, such as quotes within strings, very large numbers, Python "None" values, etc. ...

In summary:

  • Use json.dumps to create your JSON string - do not try code it manually.
  • The "\ b" does not work even though it Truth prints a plus character. The terminal protocol is which uses this character as the control code to return a position.
05.07.2018 / 16:02
0

There are two suggestions for you to use, the first one is to save direct to the file without the "," which would make things easier. If it is not possible, the second is to make a "copy" of each line and simply cut the "," of them, like this:

with open('dbname.txt', 'r+') as Arq:
    for line in Arq:
        # .split() corta a linha do arquivo exatamente no caracter ',' e forma uma lista,
        # que no seu caso tem duas partes, antes e após a virgula.
        novalinha = line.split(',')
        # Refaz tudo em outro arquivo, de maneira correta.
        with open('tmp.txt', 'w+') as NewArq:
            NewArq.write(novalinha[0] + novalinha[1])

So each line would be the same, with the difference that you would remove the "," from them, then just pass all lines to the original file again.

    
05.07.2018 / 04:54