简体   繁体   English

F#如何写入/读取CSV文件

[英]F# How to Write/Read to a CSV File

I am working on an assignment using F# where I have to add in a specific student and his information to a large Students.txt file 我正在使用F#进行作业,必须在其中将特定学生及其信息添加到大的Student.txt文件中

The Student.txt file contains their lastname, firstname, middle intial, phone number, email, and their gpa Student.txt文件包含其姓氏,名字,中间字母,电话号码,电子邮件及其gpa

A snippet of the Students.txt file Students.txt文件的摘要

If I am trying to add in this information and then read from the file: 如果我尝试添加此信息,然后从文件中读取:

type Phone = 

type Email = 

type StudentInfo =
    { firstName : string;
      middleInitial : char option;
      lastName : string;
      phone : Phone;
      email : Email option;
      gpa : float }

let addPhone input = 

let addEmail input =

let readStudentsFromCSV filename = 

let students = readStudentsFromCSV "Students.txt"

I need insight on how to write these functions. 我需要了解如何编写这些功能。 Note: This is only a snippet of my code. 注意:这只是我的代码的一部分。

There are a number of options. 有很多选择。 The main question is whether you want to write your own CSV parsing, or whether you want to use an existing library. 主要问题是您是否要编写自己的CSV解析,还是要使用现有的库。

If this is an assignment, it might require you to write your own parser (doing that would probably be a bad idea in the real world, because real world CSV files can be very messy, but it might be fine if your input is very regular). 如果这是一项任务,则可能需要您编写自己的解析器(这样做在现实世界中可能不是一个好主意,因为现实世界中的CSV文件可能非常混乱,但是如果您的输入非常常规,则可能会很好)。 If you were to use a library, the F# Data library is what most people in the F# community would use. 如果你使用的库时, F#数据库是大多数人在F#社区会用什么。

  • F# Data comes with a type provider called CsvProvider which infers the type of rows in a CSV file for you, so you do not have to write explicit type definitions. F#Data带有一个称为CsvProvider的类型提供程序,该提供程序可以为CsvProvider推断CSV文件中的行类型,因此您不必编写显式的类型定义。 (Or you can still do that, but then load data into your structures using a simple transformation.) (或者,您仍然可以这样做,但是可以使用简单的转换将数据加载到结构中。)

  • F# Data also has CsvFile type, which just does the parsing, but then returns data as a sequence of rows (which are themselves arrays of string values). F#Data也具有CsvFile类型,该类型仅进行解析,但随后将数据作为一系列行返回(它们本身是字符串值的数组)。 This might be nice if you just need something to take care of splitting the lines, but want to do the rest of the work. 如果您只需要一些东西来分割线,而又想完成其余的工作,那可能会很好。

  • If you wanted to write CSV parsing on your own, you can use File.ReadAllLines to read individual rows and then row.Split(',') to turn each row into an array of strings using , as the separator. 如果你想写CSV解析你自己,你可以使用File.ReadAllLines阅读各行,然后row.Split(',')把每行插入使用字符串数组,作为分隔符。 This could work on your file - but it will break if there is any escaping in your file (for example Foo, "a, b", Bar is just three columns! 这可能对您的文件有效-但如果文件中有任何转义符(例如Foo, "a, b", Bar仅三列),它将中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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