gpt4 book ai didi

python - 在python中将不带文件路径的文件名添加到csv

转载 作者:行者123 更新时间:2023-11-30 23:40:43 25 4
gpt4 key购买 nike

我正在使用 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(文件名)。请参阅http://docs.python.org/library/os.path.html了解更多详情。

关于python - 在python中将不带文件路径的文件名添加到csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12415540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com