Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Line From CSV File

I have .csv file with 4 columns. What's the easiest way to remove a line identical with the id of the first column? Here's where I got stuck:

if($_GET['id']) {
    $id = $_GET['id'];
    $file_handle = fopen("testimonials.csv", "rw");

    while (!feof($file_handle) ) {
        $line_of_text = fgetcsv($file_handle, 1024);    
        if ($id == $line_of_text[0]) {
            // remove row
        }
    }
    fclose($file_handle);
}

Unfortunately, databases were not a choice.

like image 589
Norbert Avatar asked Nov 01 '10 18:11

Norbert


People also ask

How do I remove the first row from a CSV file?

Read the entire CSV into a Pandas dataframe, remove the first row of the dataframe, save the entire resulting dataframe to a CSV file with the same name as in your input file. df = pd. read_csv(...,skiprows=1) ; df. to_csv('new_file.


2 Answers

$table = fopen('table.csv','r');
$temp_table = fopen('table_temp.csv','w');

$id = 'something' // the name of the column you're looking for

while (($data = fgetcsv($table, 1000)) !== FALSE){
    if(reset($data) == $id){ // this is if you need the first column in a row
        continue;
    }
    fputcsv($temp_table,$data);
}
fclose($table);
fclose($temp_table);
rename('table_temp.csv','table.csv');
like image 170
Boris Avatar answered Oct 04 '22 05:10

Boris


I recently did a similar thing in for a newsletter unsubscription, heres my code:

$signupsFile = 'newsletters/signups.csv';
$signupsTempFile = 'newsletters/signups_temp.csv';
$GLOBALS["signupsFile"] = $signupsFile;
$GLOBALS["signupsTempFile"] = $signupsTempFile;


function removeEmail($email){
    $removed = false;
    $fptemp = fopen($GLOBALS["signupsTempFile"], "a+");
    if (($handle = fopen($GLOBALS["signupsFile"], "r")) !== FALSE) {
        while (($data = fgetcsv($handle)) !== FALSE) {
        if ($email != $data[0] ){
            $list = array($data);
            fputcsv($fptemp, $list);
            $removed = true;
        }
    }
    fclose($handle);
    fclose($fptemp);
    unlink($GLOBALS["signupsFile"]);
    rename($GLOBALS["signupsTempFile"], $GLOBALS["signupsFile"]);
    return $removed;
}

this uses the temp file method of writing out the csv line by line to avoid memory errors. Then once the new file has been created, it deletes the original and renames the temp file.

You can modify this code so that it looks for an ID instead of an email address eg:

$id = $_GET['id'];  
$fptemp = fopen('testimonials-temp.csv', "a+");
if (($handle = fopen('testimonials.csv', "r")) !== FALSE) {
    while (($id= fgetcsv($handle)) !== FALSE) {
    if ($id != $data[0] ){
        $list = array($data);
        fputcsv($fptemp, $list);
    }
}
fclose($handle);
fclose($fptemp);
unlink('testimonials.csv');
rename('testimonials-temp.csv','testimonials.csv');
like image 37
Myke Black Avatar answered Oct 04 '22 07:10

Myke Black