In one of my recent project requiring a CSV text file import, the data columns had to be in certain predefined positions for the program to work correctly. The import did not depend on field labels, which is obviously a wrong way to process data. It would not have been much of a concern had the CSV files been in the correct format. However, the CSV files I had had the columns in wrong positions, which required me to exchange the columns to their correct positions for the parent program to import them correctly. For a few files I’d have easily used a spreadsheet for the task, but with around 34 files it was going to be tedious. The task entailed me to write a small script which helped in the matter.
The PHP script to exchange CSV columns is shown below.
Running the above script on the file will result in a new file with the following content.
The columns to exchange are represented by the $exchange array.
However, if we set the array to the following, the 1st and 4th columns will be reset to the original, so take care when you create the array.
The script above will not however exchange all types of CSV files; files where fields are enclosed by quotes will not work correctly with the above script. You will need to make some small modifications top the same.
Just for comparision, prior to creating the PHP script, I played around with Awk, which enabled me to accomplish the same with only two lines of code. However, I’d still prefer working with PHP, as I can easily integrate it with my other code.
How do I create a .csv file on my mac?
Thanks for sharing this. But I guess awk would an appropriate tool for this.
I prefer to use the best suited tool for a given task, maybe this approach is different than those who think that coding in a single language makes it uniform to maintain.
I did not see that you have already mentioned awk in your post. But my argument still stands valid. Let us see how python would do it.
I guess you will agree that this 7 lines of code is more elegant, readable and flexible.
The idea was not to completely reverse columns, but to exchange any two arbitrary columns.
You can save the results to a tuple and the rearrange them as you wish.
Here is how it can be done using exception handling.