-5

ディレクトリCに複数のファイルがあり、すべてのファイルを(自動的に)読み取り、各ファイルを処理してから、入力ファイルごとに出力ファイルを書き込むコードを書きたいとします。

たとえば、ディレクトリ C には次のファイルがあります。

aba 
cbr
wos
grebedit
scor

ヒント: これらのファイルには明らかな拡張子がありません

次に、プログラムはこれらのファイルを 1 つずつ読み取り、処理してから、ディレクトリに出力を書き込みます。

aba.out
cbr.out
wos.out
grebedit.out
scor.out
4

1 に答える 1

2

チュートリアルに誘導させてください。一般的なファイル IO に慣れたら、次の基本的なワークフローに進んでください。

def do_something(lines):
    output = []
    for line in lines:
        # Do whatever you need to do.
        newline = line.upper()
        output.append(newline)
    return '\n'.join(output) # 

listfiles = ['aba', 'cbr', 'wos', 'grebedit', 'scor']

for f in listfiles:
    try:
        infile = open(f, 'r')
        outfile = open(f+'.out', 'w')

        processed = do_something(infile.readlines())

        outfile.write(processed)

        infile.close()
        outfile.close()
    except:
        # Do some error handling here
        print 'Error!'

特定のディレクトリ内のすべてのファイルからリストを作成する必要がある場合は、osモジュールを使用します。

import os
listfiles = os.listdir(r'C:\test')
于 2013-03-12T19:30:45.733 に答える