如何在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}]
答案 0 :(得分:14)
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格式获取输出。
答案 1 :(得分:3)
要记录.csv不需要使用F#数据。
我更改了test的定义并添加了一些值,以便您可以编译:
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()
结果:
答案 2 :(得分:0)
这不是你的问题的答案,但它很相似,可以很方便
#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:'进程无法访问文件'C:\ Users \ User \ Desktop \ sample.csv',因为它正由另一个进程使用。'
所以我使用TextReader,可以关闭..
也许有最简单的解决方案,但我没有找到任何解决方案。