1

CSV ファイルを変更してファイル名を最後の列として追加するブレアの Python スクリプトを使用しています (以下にスクリプトを追加)。ただし、ファイル名だけを追加する代わりに、最後の列にパスとファイル名も取得します。

cmd次のコマンドを使用して、Windows 7 で以下のスクリプトを実行します。

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

1 に答える 1

3

を使用しos.path.basename(filename)ます。詳細については、 http://docs.python.org/library/os.path.htmlを参照してください。

于 2012-09-13T22:16:20.783 に答える