Python 文件夹内容 CSV 编写器

Python folder contents CSV writer

我正在尝试使用 Python 代码制作一个简单的命令行脚本,该脚本在扫描目录内容时生成 CSV,但我不确定我是否做对了,因为我不断收到错误。谁能告诉我我做错了什么?

import sys
import argparse
import os
import string
import fnmatch
import csv
from string import Template
from os import path
from os.path import basename
header = ["Title","VersionData","PathOnClient","OwnerId","FirstPublishLocationId","RecordTypeId","TagsCsv"]
if not sys.argv.len < 2:
    with open(sys.argv[1], 'w') as f:
        writer = csv.DictWriter(f, fieldnames = header, delimiter=',')
        writer.writeheader()
        if os.path.isdir(sys.argv[2]):
            for d in os.scandir(sys.argv[2]):
                row = Template('"$title","$path","$path"') #some default values in the template were omitted here
                writer.writerow(row.substitute(title=basename(d.path)), path=path.abspath(d.path))

马上,csvwriter.writerow(row) 只接受一个参数。您需要将参数括在括号内,然后用逗号连接。

此外,您不能调用行对象中的其他函数,这是您尝试使用 row.substitute(args) 等进行的操作

想通了。对于需要快速 CSV 文件夹列表的任何其他人,这是我开始工作的代码:

#!/usr/bin/env python3
import sys, os, csv
from string import Template
from pathlib import PurePath, PureWindowsPath
from os.path import basename

header = ["Title","Path","","","","",""] # insert what header you need, if any
if not len(sys.argv) < 2:
    with open(sys.argv[1], 'w') as f:
        writer = csv.DictWriter(f, fieldnames=header, dialect='excel', delimiter=',', quoting=csv.QUOTE_ALL)
        writer.writeheader()
        initPath = os.path.abspath(sys.argv[2])
        if sys.platform.startswith('linux') or sys.platform.startswith('cygwin') or sys.platform.startswith('darwin'):
            p = PurePath(initPath)
        else:
            if sys.platform.startswith('win32'):
                p = PureWindowsPath(initPath)

        if os.path.isdir(str(p)) and not str(p).startswith('.'):
            for d in os.scandir(str(p)):
                srow = Template('"$title","$path", "","","",""')
                #s = srow.substitute({'title': basename(d.path), 'path': os.path.abspath(d.path)) #
                #print(s) # this is for testing if the content produces what's expected
                row = {'Title': basename(d.path), 'Path': os.path.abspath(d.path)} # the dictionary must have the same number of entries as the number of header fields your CSV is going to contain.
                writer.writerow(row)