-1

I have a folder CSV files containing lines as follows:

Date      | A | B | C |
2021-10-11| A | B | C |

I would like to rearrange the date column across every file, for instance, from 2021-10-11 to 10/11/2021.

  • "I would like to rearrange the date column across every file" An admirable goal. What have you tried so far, and what went wrong with your attempt(s)? Please [edit] to include a [mcve] with _code_ so that we can better understand how to help – G. Anderson Oct 11 '21 at 21:37
  • @G.Anderson havent really tried not sure how – Jeremy Gorden Oct 11 '21 at 21:39
  • 1
    [How to change the datetime format in Pandas](https://stackoverflow.com/q/38067704/15497888), [Renaming column names in Pandas](https://stackoverflow.com/q/11346283/15497888), [How to read all csv files in a folder in pandas?](https://stackoverflow.com/q/65132425/15497888) – Henry Ecker Oct 11 '21 at 21:41

1 Answers1

0

Use the pathlib, datetime and csv modules

To import your data use the csv module and flip the dates you will need a csv reader and a csv writer. Using the DictReader and DictWriter classes can be convenient.

Converting dates is pretty simple using the datetime module.

import csv
from datetime import datetime

old_fmt = '%Y-%m-%d'
new_fmt = '%m/%d/%Y'

def process_file(path):
    # read the data in
    with path.open('r') as f:
        reader = csv.DictReader(f)
        fieldnames = reader.fieldnames
        data = list(reader)

    # write the data out
    with path.open('w') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        for row in data:
            # here we convert the format
            dt = datetime.strptime(row['date'], old_fmt)
            row['date'] = dt.strftime(new_fmt)
            writer.writerow(row)

pathlib is a great module for working with the filesystem. Its easy to process all the files.

from pathlib import Path

folder = Path('path/to/directory')

for path in folder.iterdir():
    if path.is_file():
        process_file(path)
Graeme Stuart
  • 5,837
  • 2
  • 26
  • 46