简体   繁体   中英

List of string in a record to CSV?

How does one write a list of string in a record to CSV without the lists being truncated?

CSV Writer:

let toSepFile sep header (fileName:string) (s:'record seq)=

    let schemaType=typeof<'record>
    let fields = Reflection.FSharpType.GetRecordFields(schemaType) 

    let toStr fields = 
        fields
        |> Seq.fold(fun res field-> res+field+sep) ""

    use w = new System.IO.StreamWriter(fileName)

    if header then 
        let header_str= fields
                    |> Seq.map(fun field -> field.Name)
                    |> toStr

        w.WriteLine(header_str)

    let elemToStr (elem:'record) = 
        //for each field get value 
        fields
        |> Seq.map(fun field -> string (FSharpValue.GetRecordField(elem,field)))
        |> toStr

    s
    |>Seq.map(elemToStr)
    |>Seq.iter(fun elem -> w.WriteLine(elem))

Test Data (Deedle test set):

let peopleRecds = 
 [ { Name = "Joe"; Age = 51; Countries = [ "UK"; "US"; "UK"] }
 { Name = "Tomas"; Age = 28; Countries = [ "CZ"; "UK"; "US"; "CZ" ] }
 { Name = "Suzanne"; Age = 15; Countries = [ "US" ] } ]

Current CSV Output:

Name    Age Countries   
"Joe    51  [CZ; UK; US; ... ]  "
"Tomas  28  [CZ; UK; US; ... ]  "
"Suzanne    15  [US]    "

So is it possible see the full list of strings from the CSV output, instead of the "..."?

Edit: Desired output:

    Name    Age Countries   
    "Joe      51    [CZ; UK; US]    "
    "Tomas    28    [CZ; UK; US; CZ]    "
    "Suzanne  15    [US]    "

The trouble you're having is that for List s, the ToString() method truncates the output. The workaround is to not use ToString() , but instead use sprint "%A" *list here* .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM