Reading specific rows (lookup) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Reading specific rows (lookup) (/thread-7294.html) |
Reading specific rows (lookup) - rumbles - Jan-03-2018 I would like to pull data from a csv, rather than manually enter date range and filename every time. In my csv, example rows: 2018, 01, 2017-12-31, 2018-01-06, filename_201801W01.csv.gz 2018, 02, 2018-01-07, 2018-01-13, filename_201801W02.csv.gz At present, I manually enter: date_ranges = [('2017-12-03', '2017-12-09')] filename = 'filename_201801W01.csv.gz' However, I would prefer to have to enter something like: Year: '2018' Week: '01' and have the dates and filename pulled from the csv Can you help? So far: with open ('DP Python dates.csv') as csvfile: readCSV = csv.reader(csvfile) datetos = [] datefroms = [] filenames = [] for row in readCSV: year = [0] week = [1] datefrom = [2] dateto = [3] filename = [4] datefroms.append(datefrom) datetos.append(dateto) filenames.append(filename) whatWeek = '01' coldex = week.index(whatWeek) coldex2 =week.index(whatWeek) theDateFrom = datefroms[coldex] theDateTo = datetos[coldex2] date_range = [(theDateFrom, theDateTo)]Then, I want something like: week = 01 date_range = [( datefrom, dateto)] filename = nameoffile Thanks RE: Reading specific rows (lookup) - hshivaraj - Jan-03-2018 Quote:In my csv, example rows: Im not sure if its just me or anybody else. I dont understand what your asking. Your question is too wage; hard to understand what your asking. Let me ask you a few questions. Am i right in thinking that your CSV file looks as follow? You want the data range and the file name retrieved when just entered the year and the week? For instance Input year: 2018 week: 01 Correct?
RE: Reading specific rows (lookup) - rumbles - Jan-03-2018 Exactly right. I’m as clear as mustard, as always. Thank you for deciphering RE: Reading specific rows (lookup) - hshivaraj - Jan-03-2018 import csv def main(): year = "2018" week = "01" results = [] with open("./files/sample.csv", "r") as fh: reader = csv.reader(fh, delimiter=',') for row in reader: row = list(map(str.strip, row)) if row[0] == year and row[1] == week: results.append((row[2] + ":" + row[3], row[4])) print(results) if __name__ == "__main__": main()Something like this |