0
import csv

rows = [["Line 5"], ["4 1.66 0 0 ! x1, x2, x3, x4"]]
        
# opening the CSV file
with open('testing.txt', 'w', newline='') as file:

# writing the CSV file
  writer = csv.writer(file, quotechar='"', quoting=csv.QUOTE_NONE, escapechar='\\')
  writer.writerows(rows)

Result:

Line 5
4 1.66 0 0 ! x1\, x2\, x3\, x4

Why there are these backslashes after x1, x2 and x3? How can I get rid of them?

Estiivan
  • 105
  • 1
  • It's because your second list in rows has commas in the string. These need to be "quoted" or "escaped" to stop them being treated as separate fields in the CSV file by using the escape character (backslash). Your code is specifically doing this. How you deal with this depends on what you intend on doing with the output file. i.e. What is the output going to be used with? To be loaded in a spreadsheet perhaps? – bigkeefer Feb 24 '23 at 13:25
  • It is a CSV text file to be submitted as a control file to a program. Because of \'s, control file does not work now. – Estiivan Feb 24 '23 at 13:37
  • writer = csv.writer(file, quotechar='"', quoting=csv.QUOTE_NONE, escapechar='\\', delimiter=';') seems to actually fix it as long there are no semicolons... – Estiivan Feb 24 '23 at 13:43

0 Answers0