Parsing CSV files back

I have csv files in the following format:

CSV FILE
"a"             , "b"     , "c" , "d"
hello, world    , 1       , 2   , 3
1,2,3,4,5,6,7   , 2       , 456 , 87
h,1231232,3     , 3       , 45  , 44

The problem is that the first field has commas "," in it. I have no control over the creation of files, as this is the format in which I receive them. Is there a way to read the CSV file back from the end of the line to the beginning?

I don't mind writing a small python script if Im being driven in the right direction.

+3
source share
8 answers

The string method rsplitbreaks the string starting on the right, not the left, and therefore it is probably what you are looking for (it takes an argument that determines the maximum number of times to split):

line = "hello, world    , 1       , 2   , 3"
parts = line.rsplit(",", 3)
print parts  # prints ['hello, world    ', ' 1       ', ' 2   ', ' 3']

, strip

parts = [s.strip() for s in parts]
print parts  # prints ['hello, world', '1', '2', '3']
+15

, , :

import csv
file = open("mycsvfile.csv")
reversedLines = [line[::-1] for line in file]
file.close()
reader = csv.reader(reversedLines)
for backwardRow in reader:
    lastField = backwardRow[0][::-1]
    secondField = backwardRow[1][::-1]
+4

- , (perl regex)

#!/usr/bin/perl

use IO::File;

if (my $file = new IO::File("test.csv"))
{
    foreach my $line (<$file>) {
    $line =~ m/^(.*),(.*?),(.*?),(.*?)$/;
    print "[$1][$2][$3][$4]\n";
    }
} else {
    print "Unable to open test.csv\n";
}

( - , 3 - ) :

+1

, .

tmp = tmp [:: - 1]

+1

, , "" . ( ) 16 , , , 16 ( ), ? , , ( ..).

+1

, CSV , , .

, :

CSV FILE
"a"             , "b"     , "c" , "d"
hello           , world   , 1   , 2   , 3
1               , 2       , 3   , 4   , 5,6,7,2,456,87
h               , 1231232 , 3   , 3   , 45,44

, , , , , , , .

, , CSV, , .

+1

, , - .

The problem is that the interface is ambiguous, and you can try to get around this, but the best solution is to try to install the interface properly (which is often more complicated than creating several patches ...).

0
source

I agree with mr beer. This is a poorly formed CSV file. It is best to find other delimiters or stop overloading commas or quote / tear out borderless commas

0
source

Source: https://habr.com/ru/post/1715085/


All Articles