CSV文件分成单独的文件

时间:2019-07-16 09:23:28

标签: python python-3.x csv python-3.7

我需要根据列值将几个csv文件分隔为传入和传出流量。此代码不提供任何输出或任何错误。

如果源== ac:37:43:9b:92:24 &&接收方地址== 8c:15:c7:3a:d0:1a,则这些行需要写入.out.csv文件。

如果发送器地址== 8c:15:c7:3a:d0:1a && Destination == ac:37:43:9b:92:24那么这些行需要写入.in.csv文件。

while read line; 
    do if -f live_photos/$line; 
             then cp live_photos/$line other_live_photos 
       fi;  done < other_live_photos.csv

enter image description here

1 个答案:

答案 0 :(得分:1)

import csv
from pathlib import Path

startdir = Path(".")
outputdir = startdir / "filtered"


def write_csv(filename, rows, fieldnames):
    # if there's nothing to write, don't write anything
    if not rows:
        return

    filename.parent.mkdir(parents=True, exist_ok=True)
    with open(filename, "w") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)


for input_filename in startdir.glob("**/*.csv"):
    with open(input_filename) as input_csv:
        inrows = []
        outrows = []

        reader = csv.DictReader(input_csv)
        for row in reader:
            if (
                row["Source address"] == "ac:37:43:9b:92:24"
                and row["Receiver address"] == "8c:15:c7:3a:d0:1a"
            ):
                outrows.append(row)

            if (
                row["Transmitter address"] == "8c:15:c7:3a:d0:1a"
                and row["Destination address"] == "ac:37:43:9b:92:24"
            ):
                inrows.append(row)

        output_filename = outputdir / input_filename.relative_to(startdir)

        write_csv(output_filename.with_suffix(".out.csv"), outrows, reader.fieldnames)
        write_csv(output_filename.with_suffix(".in.csv"), inrows, reader.fieldnames)