Menu
CoddyTech

Lectura de un archivo CSV

Parte de la sección Conceptos básicos de C# y .NET del Journey de ASP.NET Core de Coddy. Lección 16 de 20.

Los bancos y las hojas de cálculo exportan datos como CSV: un registro por línea, con comas entre los valores. File.ReadAllLines(path) devuelve las líneas de un archivo como un string[], y line.Split(',') divide una línea en cada coma:

foreach (var line in File.ReadAllLines("scores.txt"))
{
    var parts = line.Split(',');
    var points = int.Parse(parts[1]);
    Console.WriteLine($"{parts[0]} scored {points}");
}

Para una línea Ada,42, esto imprime Ada scored 42. Si el archivo no existe, se produce una excepción FileNotFoundException, así que comprueba primero File.Exists. File.ReadLines hace lo mismo, pero lee una línea a la vez, lo que resulta adecuado para archivos demasiado grandes para cargarlos en la memoria. Un archivo CSV real puede incluir comas dentro de valores entre comillas; una biblioteca CSV se encarga de eso, y los archivos de aquí no contienen ninguna.

challenge icon

Desafío

Fácil

Tu proyecto ahora tiene bank.txt, con tres gastos en formato CSV. Añade un comando import que agregue las líneas de un archivo de este tipo.

  1. Añade case "import": encima de default:. Si no se proporciona un nombre de archivo, escribe Usage: import <file> en stderr y return 1;. Si el archivo no existe, escribe No file named nope.txt. (con el nombre proporcionado) en stderr y return 1;.
  2. Para cada línea, sepárala por las comas y añade un Expense con el nombre, el importe analizado con decimal.Parse y CultureInfo.InvariantCulture, y la categoría. Cuenta las líneas que añadas.
  3. Guarda la lista una sola vez, después del bucle, e imprime:
    Imported 3 expenses from bank.txt.
  4. Añade una rama para ello en help, encima de _: help import imprime import <file>: adds the expenses in a CSV file.

Pruébalo: el terminal junto al editor ya contiene dotnet run -- import bank.txt, así que pulsa Ejecutar: la línea de arriba. Añade una línea Lamp,25.00,home a bank.txt y vuelve a pulsar Ejecutar: Imported 4 expenses from bank.txt.

Pruébalo tú mismo

using System.Globalization;
using System.Text.Json;

var file = "expenses.json";
var expenses = new List<Expense>();
if (File.Exists(file))
{
    expenses = JsonSerializer.Deserialize<List<Expense>>(File.ReadAllText(file)) ?? new List<Expense>();
}
var budgets = new Dictionary<string, decimal>();
if (File.Exists("budgets.json"))
{
    budgets = JsonSerializer.Deserialize<Dictionary<string, decimal>>(File.ReadAllText("budgets.json")) ?? new Dictionary<string, decimal>();
}
var count = expenses.Count;
var total = expenses.Sum(e => e.Amount);

if (args.Length == 0)
{
    Console.WriteLine("Expense Tracker");
    Console.WriteLine($"{count} expenses");
    Console.WriteLine($"Total: {total:F2}");
}
else
{
    switch (args[0])
    {
        case "add":
            if (args.Length < 3)
            {
                Console.Error.WriteLine("Usage: add <name> <amount> [category]");
                return 1;
            }
            if (!decimal.TryParse(args[2], CultureInfo.InvariantCulture, out var amount))
            {
                Console.Error.WriteLine($"Invalid amount: {args[2]}");
                return 1;
            }
            if (amount is <= 0 or > 10000)
            {
                Console.Error.WriteLine("The amount must be more than 0 and at most 10000.");
                return 1;
            }
            var category = args.Length > 3 ? args[3] : "other";
            var expense = new Expense(args[1], amount, category);
            expenses.Add(expense);
            File.WriteAllText(file, JsonSerializer.Serialize(expenses));
            Console.WriteLine($"Added {expense.Name}: {expense.Amount:F2} ({expense.Category})");
            if (budgets.TryGetValue(category, out var limit))
            {
                var spent = expenses.Where(e => e.Category == category).Sum(e => e.Amount);
                if (spent > limit)
                {
                    Console.WriteLine($"Over budget for {category}: {spent:F2} of {limit:F2}");
                }
            }
            break;
        case "remove":
            if (args.Length < 2)
            {
                Console.Error.WriteLine("Usage: remove <name>");
                return 1;
            }
            Expense? match = expenses.Find(e => e.Name == args[1]);
            if (match is null)
            {
                Console.Error.WriteLine($"No expense named {args[1]}.");
                return 1;
            }
            expenses.Remove(match);
            File.WriteAllText(file, JsonSerializer.Serialize(expenses));
            Console.WriteLine($"Removed {match.Name}: {match.Amount:F2}");
            break;
        case "list":
            var shown = args.Length > 1 ? expenses.Where(e => e.Category == args[1]).ToList() : expenses;
            if (shown.Count == 0)
            {
                Console.WriteLine("No expenses.");
                break;
            }
            foreach (var line in shown.Select(e => $"{e.Name}: {e.Amount:F2} ({e.Category})"))
            {
                Console.WriteLine(line);
            }
            break;
        case "top":
            var howMany = 3;
            if (args.Length > 1 && !int.TryParse(args[1], out howMany))
            {
                Console.Error.WriteLine($"Invalid number: {args[1]}");
                return 1;
            }
            var biggest = expenses.OrderByDescending(e => e.Amount).Take(howMany);
            foreach (var line in biggest.Select((e, i) => $"{i + 1}. {e.Name}: {e.Amount:F2} ({e.Category})"))
            {
                Console.WriteLine(line);
            }
            break;
        case "categories":
            var groups = expenses.GroupBy(e => e.Category).OrderByDescending(g => g.Sum(e => e.Amount));
            foreach (var g in groups)
            {
                Console.WriteLine($"{g.Key}: {g.Sum(e => e.Amount):F2} ({g.Count()})");
            }
            break;
        case "help":
            var topic = args.Length > 1 ? args[1] : "";
            var help = topic switch
            {
                "" => "Type help <command>, such as help add.",
                "add" => "add <name> <amount> [category]: saves an expense",
                "remove" => "remove <name>: deletes the first expense with that name",
                "list" => "list [category]: shows the saved expenses",
                "top" => "top [n]: shows the n biggest expenses, 3 by default",
                "categories" => "categories: shows the total of each category",
                _ => $"No help for {topic}.",
            };
            Console.WriteLine(help);
            break;
        default:
            Console.Error.WriteLine($"Unknown command: {args[0]}");
            return 1;
    }
}
return 0;

Todas las lecciones de Conceptos básicos de C# y .NET