-1

I have seen several similar posts on this but nothing has solved my problem. I am reading a list of numbers with backslashes and writing them to a .csv. Obviously the backslashes are causing problems.

addr = "6253\342\200\2236387"

with open("output.csv", 'a') as w:
  write = writer(w)
  write.writerow([addr])

I found that using r"6253\342\200\2236387" gave me exactly what I want for the output but since I am reading my input from a file I can't use raw string. i tried .encode('string-escape') but that gave me 6253\xe2\x80\x936387 as output which is definitely not what I want. unicode-escape gave me an error. Any thoughts?

Joe
  • 59
  • 1
  • 10
  • 4
    When reading from a file backslashes are **not** interpreted as Python string escapes. What makes you think that reading from the file is actually doing that? – Martijn Pieters Aug 20 '14 at 19:05
  • ^ agree. If you just print the lines from a file with lines similar to 6253\342\200\2236387, you'll see the \'s print just fine. Just iterate the file, strip() the lines and split('\\') and you'll get a list of the numbers. – ScottO Aug 20 '14 at 19:17
  • Im getting this error UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 4: ordinal not in range(128) So it appears to be reading it as a dash rather than an escape character. – Joe Aug 20 '14 at 19:42
  • Show us the actual code that you're trying to run along with part of your input file. – jwodder Aug 20 '14 at 20:38

3 Answers3

0

The r in front of a string is only for defining a string. If you're reading data from a file, it's already 'raw'. You shouldn't have to do anything special when reading in your data.

Note that if your data is not plain ascii, you may need to decode it or read it in binary. For example, if the data is utf-8, you can open the file like this before reading:

import codecs
f = codecs.open("test", "r", "utf-8")
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
-1

Text file contains...

1234\4567\7890
41\5432\345\6789

Code:

with open('c:/tmp/numbers.csv', 'ab') as w:
    f = open(textfilepath)
    wr = csv.writer(w)
    for line in f:
        line = line.strip()
        wr.writerow([line])
    f.close()

This produced a csv with whole lines in a column. Maybe use 'ab' rather than 'a' as your file open type. I was getting extra blank records in my csv when using just 'a'.

ScottO
  • 129
  • 4
-1

I created this awhile back. This helps you write to a csv file.

def write2csv(fileName,theData):

    theFile = open(fileName+'.csv', 'a')

    wr = csv.writer(theFile, delimiter = ',', quoting=csv.QUOTE_MINIMAL)

    wr.writerow(theData)
kelvin
  • 1
  • 3