我正在使用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:])
實際上,一旦我通過使用os.chdir() –