1

我正在使用 Blair 的 Python 脚本,它修改 CSV 文件以将文件名添加为最后一列(脚本附加在下面)。但是,我不是单独添加文件名,而是在最后一列中获取路径和文件名。

cmd我使用以下命令在 Windows 7 中运行以下脚本:

python C:\data\set1\subseta\add_filename.py C:\data\set1\subseta\20100815.csv

生成的 ID 字段由以下内容填充C:\data\set1\subseta\20100815.csv,但我只需要20100815.csv.

我是python的新手,所以任何建议都值得赞赏!

import csv
import sys

def process_file(filename):
    # Read the contents of the file into a list of lines.
    f = open(filename, 'r')
    contents = f.readlines()
    f.close()

    # Use a CSV reader to parse the contents.
    reader = csv.reader(contents)

    # Open the output and create a CSV writer for it.
    f = open(filename, 'wb')
    writer = csv.writer(f)

    # Process the header.
    header = reader.next()
    header.append('ID')
    writer.writerow(header)

    # Process each row of the body.
    for row in reader:
        row.append(filename)
        writer.writerow(row)

    # Close the file and we're done.
    f.close()

# Run the function on all command-line arguments. Note that this does no
# checking for things such as file existence or permissions.
map(process_file, sys.argv[1:])
4

1 回答 1

3

使用os.path.basename(filename). 有关更多详细信息,请参阅http://docs.python.org/library/os.path.html

于 2012-09-13T22:16:20.783 回答