python-用分隔符在CSV文件中分割字符串

时间:2019-02-06 03:54:05

标签: python file csv split

我有一个包含以下数据的CSV文件:

move_pages()

我已像这样将文件导入python:

Date,Profit/Losses
Jan-10,867884
Feb-10,984655
Mar-10,322013
Apr-10,-69417
May-10,310503
Jun-10,522857
Jul-10,1033096
Aug-10,604885
Sep-10,-216386
Oct-10,477532
Nov-10,893810
Dec-10,-80353

我需要遍历这些行,以便仅提取月份(即“ Jan”,“ Feb”等)并将其放在其他列表中。我还必须以某种方式跳过第一行,即with open(csvpath, 'r', errors='ignore') as fileHandle: lines = fileHandle.read() ,它是标题。

这是我到目前为止编写的代码:

Date, Profit/Losses

但是,当我尝试打印months = [] for line in lines: months.append(line.split("-") 列表时,它会分割文件中的每个字符! 我在哪里错了?

4 个答案:

答案 0 :(得分:1)

您的问题的一个答案是使用fileHandle.readlines()

lines = fileHandle.readlines()
# print(lines)
# ['Date,Profit/Losses\n', 'Jan-10,867884\n', 'Feb-10,984655\n', 'Mar-10,322013\n',
#  'Apr-10,-69417\n', 'May-10,310503\n', 'Jun-10,522857\n', 'Jul-10,1033096\n', 'Aug-10,604885\n',
#  'Sep-10,-216386\n', 'Oct-10,477532\n', 'Nov-10,893810\n', 'Dec-10,-80353\n']

for line in lines[1:]:
    # Starting from 2nd item in the list since you just want months
    months.append(line.split("-")[0])

答案 1 :(得分:1)

您几乎可以始终使用专用工具(例如csv模块和列表理解)来减轻痛苦:

import csv
with open("yourfile.csv") as infile:
    reader = csv.reader(infile) # Create a new reader
    next(reader) # Skip the first row
    months = [row[0].split("-")[0] for row in reader]

答案 2 :(得分:0)

如果您真的想用困难的方式尝试它,请尝试以下操作:

$(document).ready(function() {
  var barStyle = {
    scaleLineColor: "rgba(0,0,0,0)",
    scaleShowLabels: true,
    scaleShowGridLines: false,
    pointDot: false,
    datasetFill: false,
    // Sadly if you set scaleFontSize to 0, chartjs crashes
    // Instead we'll set it as small as possible and make it transparent
    scaleFontSize: 9,
  };

  $(".barchart").each(function() {
    //Get context with jQuery - using jQuery's .get() method.
    var ctx = $(this)
      .get(0)
      .getContext("2d");
    //This will get the first returned node in the jQuery collection.
    var myNewChart = new Chart(ctx);   
    // Get the chart data and convert it to an array
    var chartData = $(this).data("chart");

    // Build the data object
    var data = {};
    var labels = [];
    var datasets = {};

    // Create a null label for each value
    for (var i = 0; i < chartData.length; i++) {
      labels.push("");
    }

    // Create the dataset
    datasets["strokeColor"] = 'rgba(54, 162, 235, 0.2)';
    datasets["data"] = chartData;    

    // Add to data object
    data["labels"] = $(this).data("label");
    data["datasets"] = Array(datasets);

    new Chart(ctx).Bar(data, barStyle);
  });
});

months = [] for line in lines[1:]: months.append(line.split("-")[0]) 将跳过第一行,而lines[1:]仅提取月份并追加到您的列表line.split("-")[0]

但是,按照AChampion的建议,您应该真正研究monthscsv软件包。

答案 3 :(得分:0)

这应该可以达到预期的效果(假设在同一目录中名为data.csv的文件):

result = []

with open('data.csv', 'r', encoding='UTF-8') as data:
    next(data)
    for record in data:
        result.append(record.split('-')[0])