Dart 在处理 CSV 文件时存在问题

问题描述 投票:0回答:1

我有以下 CSV 文件

$ cat ../SyncedShazams.csv
"artist","title","status","date","longitude","latitude"
"Queen","Fat Bottomed Girls","N/A","2024-04-09T22:03:30.164Z","N/A","N/A"
"W&W & AXMO","Heaven Is a Place On Earth","N/A","2024-04-09T21:59:34.614Z","N/A","N/A"
"Kleks & sanah","Jestem Twoją Bajką","N/A","2024-04-07T05:07:22.333Z","N/A","N/A"
"Oskar Cyms","Nigdy wcześniej","N/A","2024-04-06T04:49:43.106Z","N/A","N/A"
"Heidi Montag","I'll Do It","N/A","2024-04-04T07:23:10.340Z","N/A","N/A"
"vowl. & Sace","2000","N/A","2024-04-04T07:22:53.608Z","N/A","N/A"
"City High","What Would You Do?","N/A","2024-04-03T20:22:52.658Z","N/A","N/A"
"City High","What Would You Do?","N/A","2024-04-03T20:22:32.131Z","N/A","N/A"
"Kleks, IGO, Kaśka Sochacka, Mrozu, Artur Rojek, Brodka, Ralph Kaminski, Bedoes 2115 & Sokół","Całkiem Nowa Bajka","N/A","2024-03-29T23:39:11.413Z","N/A","N/A"

必须按如下方式转换列:

Queen - Fat Bottomed Girls
Kleks, IGO, Kaśka Sochacka, Mrozu, Artur Rojek, Brodka, Ralph Kaminski, Bedoes 2115 & Sokół - Całkiem Nowa Bajka

但是,当前的 Dart 代码仅打印

HELLO

$ cat bin/shazam.dart
import 'package:shazam/shazam.dart' as shazam;
import 'dart:io';
import 'package:csv/csv.dart';

void main() async {
  try {
    final String csvData = await readFile('../SyncedShazams.csv'); 
    final List<List<dynamic>> rows = const CsvToListConverter().convert(csvData);
    print("HELLO");
  
    // Skip the header and process each row
    for (var row in rows.skip(1)) {
      if (row.length > 1) {
        // Artists and song title are expected to be in the first and second columns respectively
        print('${row[0]} - ${row[1]}');
      }
    }
  } catch (e) {
    print('Failed to process CSV: $e');
  }
}

Future<String> readFile(String filePath) async {
  final file = File(filePath);
  try {
    return await file.readAsString();
  } catch (e) {
    throw Exception('Failed to read the file: $e');
  }
}

飞镖输出:

$ dart run
Building package executable... 
Built shazam:shazam.
HELLO

我错过了什么?

dart
1个回答
0
投票

下载 CSV 文件后,问题似乎确实是行结尾,正如 jamesdlin 指出的那样,

我使用 CRLF 行结尾 (

\r\n
),而您的文件使用 LF 行结尾 (
\n
)。

这里有 2 种可能的解决方案。

  1. 将文件转换为使用

    \r\n
    行结尾。

  2. 更新代码以期望

    \n
    行结尾。 事实证明,默认情况下
    CsvToListConverter()
    需要
    \r\n
    ,但您可以传入
    eol
    命名参数,如下所示
    CsvToListConverter(eol: '\n')

© www.soinside.com 2019 - 2024. All rights reserved.