add file name without file path to csv in python
Question: I am using Blair's Python script which modifies a CSV file to add the filename
as the last column (script appended below). 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:

    
    
    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`.

I'm new to python so any suggestion is appreciated!

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


Answer: Use `os.path.basename(filename)`. See
<http://docs.python.org/library/os.path.html> for more details.

