【问题标题】:Python folder contents CSV writerPython 文件夹内容 CSV 编写器
【发布时间】:2015-11-10 04:10:07
【问题描述】:

我正在尝试使用 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))

【问题讨论】:

    标签: csv python-3.x command-line directory directory-structure


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      想通了。对于其他需要快速 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)
      

      【讨论】:

        猜你喜欢
        • 2011-11-16
        • 2018-09-07
        • 1970-01-01
        • 2021-08-15
        • 2019-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多