2017-01-20 9 views
0

ファイル名がfile_1.txt, file_2.txt, file_3.txt .....file_n.txtのディレクトリにnというファイルがあるとします。私は個別のPythonにインポートし、それらにいくつかの計算を行い、その後、n対応する出力ファイルに結果を保存したいと思います:file_1_o.txt, file_2_o.txt, ....file_n_o.txt.ファイル名が異なる複数のファイルをエクスポートする

私は複数のファイルをインポートする方法を考え出した:

import glob 
import numpy as np 

path = r'home\...\CurrentDirectory' 
allFiles = glob.glob(path + '/*.txt') 
for file in allFiles: 
    # do something to file 
    ... 
    ... 
    np.savetxt(file,) ??? 

出力ファイルがfile_1_o.txt

答えて

2

になるように、ファイル名の後ろに_o.txt(またはそれに関係する文字列)を追加する方法が不明です出力ファイル名を作成するには、次のスニペットを使用できますか?

parts = in_filename.split(".") 
out_filename = parts[0] + "_o." + parts[1] 

ここで、in_filenameは "file_1.txt"という形式です。
もちろん、"_o."(拡張子の前にある接尾辞)を変数に入れて、ただちに変更してその接尾辞をより簡単に変更できるようにする方がいいでしょう。 あなたのケースでは、

import glob 
import numpy as np 

path = r'home\...\CurrentDirectory' 
allFiles = glob.glob(path + '/*.txt') 
for file in allFiles: 
    # do something to file 
    ... 
    parts = file.split(".") 
    out_filename = parts[0] + "_o." + parts[1] 
    np.savetxt(out_filename,) ??? 

を意味していますがnp.savetxtout_filenameを渡す前に、多分あなたは、あなたが
np.savetxt(os.path.join(path, out_filename),)
か何かのようなものを持っている必要がある場合がありますので、完全なパスを構築する必要があるので、あなたは、注意する必要がありますそれらの行に沿って。
あなたが使用して同じことをやって別の方法を使用しています

hh = "_o." # variable suffix 
.......... 
# inside your loop now 
for file in allFiles: 
    out_filename = hh.join(file.split(".")) 

のようなものを持っていることができる前に私が述べたように、基本的には、1つのラインの変化を組み合わせて、「変数に接尾辞」あなたを定義したい場合彼の答えで@NathanAckが述べたように、分割されたリストに参加してください。

0
import os 

#put the path to the files here 
filePath = "C:/stack/codes/" 
theFiles = os.listdir(filePath) 

for file in theFiles: 
    #add path name before the file 
    file = filePath + str(file) 

    fileToRead = open(file, 'r') 
    fileData = fileToRead.read() 

    #DO WORK ON SPECIFIC FILE HERE 
    #access the file through the fileData variable 
    fileData = fileData + "\nAdd text or do some other operations" 

    #change the file name to add _o 
    fileVar = file.split(".") 
    newFileName = "_o.".join(fileVar) 

    #write the file with _o added from the modified data in fileVar 
    fileToWrite = open(newFileName, 'w') 
    fileToWrite.write(fileData) 

    #close open files 
    fileToWrite.close() 
    fileToRead.close() 
関連する問題