Created
January 11, 2024 10:03
-
-
Save max747/cf0fe3289ecac33798f18244d4cb88bd to your computer and use it in GitHub Desktop.
zip ファイル内に含まれる特定の CSV ファイルを明示して読み取る例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
zip ファイル内に含まれる特定の CSV ファイルを明示して読み取る例 | |
""" | |
import argparse | |
import csv | |
import io | |
import zipfile | |
def main(args): | |
with zipfile.ZipFile(args.zipfile) as zf: | |
if args.csvfile not in zf.namelist(): | |
print(f"{args.csvfile} not found in {args.zipfile.name}") | |
return | |
with zf.open(args.csvfile) as f: | |
reader = csv.reader(io.TextIOWrapper(f, encoding=args.csv_encoding)) | |
for row in reader: | |
print(row) | |
def parse_args(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("zipfile", type=argparse.FileType("rb")) | |
parser.add_argument("csvfile") | |
parser.add_argument("--csv-encoding", default="utf-8") | |
return parser.parse_args() | |
if __name__ == "__main__": | |
main(parse_args()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment