简体   繁体   中英

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

The Student.txt file contains their lastname, firstname, middle intial, phone number, email, and their gpa

A snippet of the Students.txt file

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.

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). If you were to use a library, the F# Data library is what most people in the F# community would use.

  • 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. (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). 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. 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!

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