English 中文(简体)
prevent CRLF in CSV export data
原标题:
  • 时间:2009-11-27 13:50:45
  •  标签:
  • csv
  • newline

I have an export functionality that reads data from DB (entire records) and writes them in a .txt file, one record on a row each field being separated by ; . the problem i am facing is that some fields contain CRLFs in it and when i write them to the file it goes to the next line thus destroying the structure of the file.

The only solution is to replace the CRLFs with a custom value, and at import replace back with CRLF. but i don t like this solution because these files are huge and the replace operation decreases performance....

Do you have any other ideas?

thank you!

最佳回答

Yes, use a CSV generator that quotes string values. For example, Python s csv module.

For example (ripped and modified from the csv docs):

import csv
def write(filename):
    spamWriter = csv.writer(open(filename,  w ), quoting=csv.QUOTE_ALL)
    spamWriter.writerow([ Spam ] * 5 + [ Baked Beans ])
    spamWriter.writerow([ Spam ,  Lovely Spam ,  Wonderful Spam
bar ])

def read(filename):
    reader = csv.reader(open(filename, "rb"))
    for row in reader:
        print row

write( eggs.csv )
read( eggs.csv )

Outputs:

[ Spam ,  Spam ,  Spam ,  Spam ,  Spam ,  Baked Beans ]
[ Spam ,  Lovely Spam ,  Wonderful Spam
bar ]
问题回答

If you have control over how the file is exported and imported, then you might want to consider using XML .. also you can use double quotes i believe to indicate literals like "," in the values.





相关问题
Styling rows in table that uses CSV data through PHP

I ve been working on this simple code that puts a CSV file into a nice table. But because the data is imported, styling ODD rows is a pretty hard thing to do. All I need would be a method to address ...

PHP - Sanitise a comma separated string

What would be the most efficient way to clean a user input that is a comma separated string made entirely on numbers - e.g 2,40,23,11,55 I use this function on a lot of my inputs function clean($...

marking duplicates in a csv file

I m stumped with a problem illustrated in the sample below: "ID","NAME","PHONE","REF","DISCARD" 1,"JOHN",12345,, 2,"PETER",6232,, 3,"JON",12345,, 4,"PETERSON",6232,, 5,"ALEX",7854,, 6,"JON",12345,, ...

Interactive heat map in Flex

I’m at a very basic level with Flex and with programming in general. I am working on a project where I have data in an Excel (.csv) format, it’s a large Excel plot/matrix where each cell has a ...

热门标签