string manipulation python

Asked

Viewed 551 times

2

I am having a problem regarding python b (Backspace), instead of deleting the previous character, it generates a "•" as the image below:

inserir a descrição da imagem aqui

Follow the line of the code that generates this return:

     #-*- coding: utf-8 -*-
import pyodbc
import platform
import json
#------------------------------------------------------#
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 case, I’m using b to erase that comma.

Thanks in advance!

NOTE: Python version 3.7

  • Actually this is the graphic character equivalent to ASCII 8, see here: https://upload.wikimedia.org/wikipedia/commons/f/f8/Codepage-437.png. It seems that you are saving the file to disk and not displaying ito on the screen, soon it is more practical you cut this character before printing instead of trying to "cut it" inside the file.

  • How can I do that?

  • Voc}and is subject to glaring errors already in line open("C:\Zabbix\prm2.txt", 'r') - precisely why the \ is escape prefix for some special characters - use either "/" forward - is compatible even in Windows, or a string with prefix "r" : open(r"C:\Zabbix\prm2.txt", 'r')

2 answers

3

There is a concept error there - the " b" is simply a control character, named "Backspace", which has decimal code "8" - when printed in a terminal , the terminal protocol is what causes the previous character to be deleted.

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

That is, what you need to do is not write the unwanted comma to the file to begin with. You have not added more parts to your program, so you can’t tell exactly where you can do this, but in general it will require you to have a vailable "counter", and record the comma at the beginning of each item, if that item nay is the first.

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

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

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

An even better alternative, if you are creating a JSON file is to let Python transform a "live" data structure, composed of dictionaries and lists into the JSON string.

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

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

In short:

  • Use the json.dumps to create your JSON string - do not try code it manually.
  • The " b" doesn’t even work because it na truth prints a character the most. The terminal protocol is that uses this character as a control code to return a position.
  • Caraa first thank you so much for your help your explanation gave me a Light! And I complicated a lot without the code I ask forgiveness, I have already edited and put all my source code to better exemplify my doubt,

  • About the use of import json I tried but there are some changes in the JSON version for JSON RPC 2

  • I find it very unlikely that the json consumed by the specific protocol is not valid JSON - it can be a valid Json subset. In addition, the Python json module has enough flexibility to customize serialization - I doubt very much that you cannot use it. I would recommend you try using the Python json, and if you have a mistake, create another question including the specific errors. (Leave that as it is - we clarified the " b" here)

  • OK I will do this, I will study a little more about serialization and if I find problem I create a new question Thank you

0

There are two suggestions for you to use, the first is to save straight 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 their "," thus:

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, except that you would delete the "," from them, then just pass all the lines to the original file again.

  • Your suggestion was perfect however, the file is a JSON RPC 2, there has to be a comma in each line, only in the last line that does not have, follows an example of what I am doing: this is the code: { "date": [ { "{#HOST}": "Japan 1", "{#COUNT}": "5" }, { "{#HOST}": "Japan 2", "{#COUNT}": "12" }, { "{#X A}": "Latvia", "{#COUNT}": "3" } ] } note that in the last data line there is no comma, and in the JSON validator d error with the last one ",

  • I don’t even know how to manipulate this type of JSON file, but you couldn’t fix it in txt and then turn it into JSON? Maybe it would help by facilitating the process, or maybe there’s a simpler method by manipulating the file itself that I don’t know about.

  • I already did it, I did it like this: I locate the last line, delete it and out of print the last line without the comma in case

Browser other questions tagged

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