0

I want to write special characters in a file with \ before them. What is the best way to do it?

Simple example:

x = open('file.txt','w')
a = "abc's"
x.write(a)

Current output:

abc's

Expected output:

abc\\'c

More details:

I'm working with openpyxl and I have 5000 rows and more than 50 columns and I need to make a program that will rewrite it to SQL

x = open('file.txt', 'w', encoding='utf-8')
file_object = openpyxl.load_workbook("excel.xlxs".strip())
sheet_obj = file_object.active
max_column = sheet_obj.max_column
max_row = sheet_obj.max_row

for row in range(1, max_row+1):
    title = sheet_obj.cell(row=row, column=1)
    print(title.value)

Current output

a = 'example_"example"_example'

INSERT INTO table VALUES("example_"example"_example")

Expected output

a = 'example_\"example\"_example'

INSERT INTO table VALUES("example_\"example\"_example")

Conclusion

Is there a way to do it faster than making a function that would do it by going by one character

def main(string: str):
    output = ""
    for i in str(string):
        if i in ["'", '"', '%']:
            output += '\\' + i
        else:
            output += i
    return output
Luca Clissa
  • 810
  • 2
  • 7
  • 27
Gren Man
  • 110
  • 9

0 Answers0