2017-11-16 5 views
0

私はPythonを学習していて、英語もしています。そして私は簡単かもしれない問題を抱えていますが、解決できません。私は.TXT年代のフォルダを持っている 、私は各one.Iの17個の数字のシーケンスは、私が.txtの名前を変更したときに空のファイルを作成する

import os 
import re 

path_txt = (r'C:\Users\usuario\Desktop\files') 


name_files = os.listdir(path_txt) 


for TXT in name_files: 
    with open(path_txt + '\\' + TXT, "r") as content: 
     search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read()) 
     if search is not None: 
      print(search.group(0)) 
      f = open(os.path.join("Processes" , search.group(0) + ".txt"), "w") 
     for line in content: 
      print(line) 
      f.write(line) 
      f.close() 

その作成から抽出されたシーケンスで、各ファイルの名前を変更する必要があり、正規表現で抽出することができました。 txtは "Processes"フォルダには空ですが、必要な名前を付けました。

PS:Pythonの3

+0

を 'open'が与えられた名前で*新しいファイル*を作成します、それはあなたのファイルの名前を変更しません。あなたは['os.rename'](https://stackoverflow.com/questions/2759067/rename-multiple-files-in-a-directory-in-python)を見てください。ちょっとした調整が必要です現時点では得られている。 – hnefatl

答えて

0

を使用してあなたがファイルの名前を変更できません。代わりに、の書き込みモードのファイルを開きます。ファイルがまだ存在しない場合は作成されます。あなたはファイルrenameしたい代わりに

# search the file for desired text 
with open(os.path.join(path_txt, TXT), "r") as content: 
    search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read()) 

# we do this *outside* the `with` so file is closed before rename 
if search is not None: 
    os.rename(os.path.join(path_txt, TXT), 
     os.path.join("Processes" , search.group(0) + ".txt")) 
+0

ご協力ありがとうございます。 トレースバック(最後の最新の呼び出し):: ファイル「」、7行目、 FileExistsError中:[WinError 183]既に存在するファイルを作成できません:「C:\\ユーザーが今では別のエラーを返します。 \ 彼は繰り返しの順序で文書を見つけたので私は思う。その場合、名前を変更するにはどうすればよいですか?たとえば、1234 .... copy(1); 1234 ....コピー(2); –

関連する問題