![](/img/trans.png)
[英]Python: add column to loaded csv file without changing the csv file
[英]add file name without file path to csv in python
我正在使用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:])
使用os.path.basename(filename)
。 有關詳細信息,請參閱http://docs.python.org/library/os.path.html 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.