将自定义分隔符添加回csv?

时间:2018-11-26 20:46:35

标签: python csv

当前,我使用自定义定界符“ |”导入一个csv文件。然后,我阅读并使用以下代码对其进行修改:

import csv


ChangedDate = '2018-10-31'

firstfile  = open('example.csv',"r")
firstReader = csv.reader(firstfile, delimiter='|')
firstData = list(firstReader)
outputFile = open("output.csv","w")

iteration = 0

for row in firstData:
    firstData[iteration][25] = ChangedDate
    iteration+=1

outputwriter = csv.writer(open("output.csv","w"))

outputwriter.writerows(firstData)
outputFile.close()

但是,当我将行写入输出文件时,它们之间用逗号分隔。这是一个问题,因为我正在处理大量财务数据,因此逗号很自然地出现,例如$ 8,000.00,因此“ |”原始文件的分隔符。在将列表写入输出文件之前,有没有办法“重新定界”我的列表?

1 个答案:

答案 0 :(得分:0)

您可以将delimiter提供给csv.writer

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>

#define BUFFER_SIZE 256


void swap(char** a, char** b) {
    char* temp = *a;
    *a = *b;
    *b = temp;
}

char* getLongestString(char** strings, int size) {
    char* max = strings[0];
    for (int i = 1; i < size; i++) {
        if (strlen(max) < strlen(strings[i])) {
            max = strings[i];
        }
    }
    return max;
}

void sortStrings(char** strings, int size) {
    bool changed = true;
    while (changed) {
      changed = false;
        for (int i = 0; i < size - 1; i++) {
          if (strcmp(strings[i], strings[i + 1]) >= 0) {
            swap(&strings[i], &strings[i + 1]);
            changed = true;
          }
        }
    }
}

int readSize() {
  int size = 0;
  printf("Enter number of strings:\n");
  scanf("%d", &size);
  return size;
}

void printResults(char** words, int size) {
    char* longest = getLongestString(words, size);
    printf("The longest word is: %s\n", longest);
    sortStrings(words, size);
    //printf("The maximal word lexicographically is: %s\n", words[size]);
    printf("The minimal word lexicographically is: %s\n", words[0]);
}