2012-09-13 98 views
1

我正在使用Blair的Python腳本,它修改了一個CSV文件以將文件名添加到最後一列(下面附加的腳本)。但是,不是單獨添加文件名,而是在最後一列中獲取路徑和文件名。在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

我是新來的蟒蛇,所以任何建議表示讚賞!

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

實際上,一旦我通過使用os.chdir() –

回答

3

使用os.path.basename(filename)。有關更多詳細信息,請參閱http://docs.python.org/library/os.path.html

+1

將工作目錄更改爲腳本所在的位置,請注意,如果您在Unix系統上測試此目錄,則必須記住使用'ntpath'我剛剛犯的錯誤..) – DSM