extract rows and filenames from multiple csv files

后端 未结 5 441
醉酒成梦
醉酒成梦 2021-01-17 02:28

I have multiple csv files with date as filename (20080101.csv to 20111031.csv) in a folder. The csv files have common headers. The csv file looks like this:



        
5条回答
  •  旧时难觅i
    2021-01-17 02:40

    This is a well-formed question, from which the logic should be apparent. For someone to provide finished code would defeat the purpose of the assignment. First, add a "homework" tag to the question, then think about what you want to do: 1) loop over the files (keeping track of each filename as it's opened) 2) read lines from the current file 3) if the selection criteria (x==1 and y==2) is met, then write the line.

    To get started, try:

    import csv, os
    
    for fn in os.listdir():
        if ".csv" in fn:
            with open(fn, 'r', newline='') as f:
                reader = csv.reader(f, delimiter=";")
                for row in reader:
                    ...
    

    Then extend the solution to open the output file and write the selected lines using csv.writer.

提交回复
热议问题