简体   繁体   中英

Python reading and writing a csv file working with dates

I would like to see in python, the code that reads a csv file containing years of historical dates with a value (example of each line: 2016-09-23,2173.290039) , this code would then write another csv file with every date and its associated value that occurs on a Friday. Thank you so much for your help.

The following script will do what you need:

from datetime import datetime   
import csv

with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)

    for row in csv_input:
        if datetime.strptime(row[0], "%Y-%m-%d").weekday() == 4:       # if Friday
            csv_output.writerow(row)

If input.csv contains:

2016-09-23,2173.290039
2016-09-24,2174.290039
2016-09-25,2175.290039
2016-09-26,2176.290039

It will create output.csv containing:

2016-09-23,2173.290039  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM