在python中添加没有文件路径的文件名到csv

时间:2012-09-13 22:12:45

标签: python csv

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

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

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:])

1 个答案:

答案 0 :(得分:3)

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