如何在 f# 中创建 CSV 文件并将数据写入

How to create a CSV file and write data into in f#

如何在 f sharp 中创建一个 csv 文件并在其中写入以下记录类型?

    type test = { G:array<double>; P:array<double>; GG:array<double>; PP:array<double> } 

    let table = [for x in 0..(Un0.Length - 1) -> 
        let b = Un0.[x] in 
        if b=0.0 then {G=0.0; P=0.0; GG=0.0; PP=0.0}
        else {G=G_0.[x]/b; P=P0.[x]/b; GG=G0.[x]/b; PP=PP0.[x]/b}]

CSV type provider from FSharp.Data 主要用于读取 CSV(顾名思义),但它也能够写入 CSV。

您需要做的就是定义类型,或者通过提供示例 .CSV 文件

let titanic2 = CsvProvider<"../data/Titanic.csv", Schema="Fare=float,PClass->Passenger Class">.GetSample()

或直接定义模式

type MyCsvType = CsvProvider<Schema = "A (int), B (string), C (date option)", HasHeaders=false>

然后您可以创建一个记录对象并填充它(以类型安全的方式!)

// you can build the rows themselves
let myCsv = new MyCsvType( [ MyCsvType.Row(1, "a", None)
                             MyCsvType.Row(2, "B", Some DateTime.Now) ])

// or, for your scenario, you probably want to define a conversion function
// from your record type to the CSV provider's type
let buildRowFromObject obj = MyCsvType.Row(obj.A, obj.B, obj.C)

let buildTableFromObjects = (Seq.map buildRowFromObject) >> Seq.toList >> MyCsvType

let myCsv = someSequenceOfObjects |> buildTableFromObjects

最后,只需致电

myCsv.SaveToString()

获取 CSV 格式的输出。

无需使用 F# 数据以 .csv 格式记录。

我更改了测试的定义并添加了一些值以便您可以编译:

type test = { G:double; P:double; GG:double; PP:double }
            override this.ToString() = 
                sprintf "%f;%f;%f;%f\n" this.G this.P this.GG this.PP

let G_0  =  [|(0.0)..(10.0)|]
let Un0  =  [|(1.0)..(11.0)|]
let P0   =  [|(2.0)..(12.0)|]
let G0   =  [|(3.0)..(13.0)|]
let PP0  =  [|(4.0)..(14.0)|]

let table = [for x in 0..(Un0.Length - 1) -> 
                let b = Un0.[x] 
                if b=0.0 then {G=0.0; P=0.0; GG=0.0; PP=0.0}
                else {G=G_0.[x]/b; P=P0.[x]/b; GG=G0.[x]/b; PP=PP0.[x]/b}]

let wr = new System.IO.StreamWriter("Csv.csv")
table |> List.map(string) |> String.concat("") |> wr.Write
wr.Close()

结果:

这不是您问题的确切答案,但它很相似并且可以派上用场

如何使用 f# CSV 类型提供程序编辑 csv 文件

解决方案:

#r "..\packages\FSharp.Data.2.3.3\lib\net40\FSharp.Data.dll"
open System.IO
open FSharp.Data

type CsvTest = CsvProvider<"""C:\Users\User\Desktop\sample.csv""">
let textReader = File.OpenRead("""C:\Users\User\Desktop\sample.csv""")// need to use TextReader
let csvTest = CsvTest.Load(textReader)
let modified = csvTest.Append [CsvTest.Row(3,"bum") ]// add row to csv
textReader.Close()// closing file before edit...
modified.Save   """C:\Users\User\Desktop\sample.csv""" //save it

您可能需要重置交互式会话(如果您使用 fsx)

解释:

像这样直接加载文件:

let csvTest = CsvTest.Load("""C:\Users\User\Desktop\sample.csv""")

无效。如果你尝试它,你会得到错误:

System.IO.IOException: 'The process cannot access the file 'C:\Users\User\Desktop\sample.csv' because it is being used by another process.'

所以我用的是TextReader,可以关闭..

也许有最简单的解决方案,但我没有找到。