简体   繁体   English

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

[英]add file name without file path to csv in python

I am using Blair's Python script which modifies a CSV file to add the filename as the last column (script appended below). 我正在使用Blair的Python脚本修改CSV文件,将文件名添加为最后一列(下面附加脚本)。 However, instead of adding the file name alone, I also get the Path and File name in the last column. 但是,我不是单独添加文件名,而是在最后一列中获取路径和文件名。

I run the below script in windows 7 cmd with the following command: 我使用以下命令在Windows 7 cmd运行以下脚本:

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

The resulting ID field is populated by the following C:\\data\\set1\\subseta\\20100815.csv , although, all I need is 20100815.csv . 生成的ID字段由以下C:\\data\\set1\\subseta\\20100815.csv ,但我需要的只是20100815.csv

I'm new to python so any suggestion is appreciated! 我是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:])

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM