2016-07-08 11 views
0

私はPythonには新しく、ある場所から別の場所にいくつかのファイルをコピーして、mysqlデータベースの中にいくつかの情報を保存したいと思います。スクリプトが動作するまで2回スクリプトを実行する必要があります。最初の試行の後、最初のfor-loopの直後で停止します。それを2回目に実行するとすべてが終了します。pythonスクリプトは2つのループの間で終了します

import re, shutil, glob, os, MySQLdb 
db = MySQLdb.connect(host = "localhost",user = "root",passwd = "xxx",db = "test") 
x = db.cursor() 

delete = """DELETE FROM import WHERE fehler = '1'""" 
x.execute(delete) # clear the table 

dest = 'local' # paths 
path = 'local/*.txt' # paths 
files = glob.glob(path) # paths 

for orig in glob.glob(r'/mnt/sap01x/OUT/INT/success/*.txt'): 
    shutil.copy2(orig, dest) # copy all files from one to another dir 

for file in files: # starting to scan the files 
    f = open(file, 'r') 
    lines = f.read() 
    output = re.search(r'error', lines) # regexp to search for 'error' 
    if output: 
     query = """INSERT INTO import (Fehler,Filename) VALUES ("1","%s")""" 
      x.execute(query, file) # insert error to db 
      db.commit() 
      os.remove(file) # remove file 
    else: 
      os.remove(file) # remove file 

db.close() 

私が間違っていることをアドバイスできますか?

+5

ファイルをコピーする前にリストします。したがって、 'files'は空のリストです。 2つのループの間に 'files = glob.glob(path)'を移動するか、最初のループでコピーしたすべてのファイルのリストを作成し、2番目のループでそれを使用するだけです( 'files = []'最初のループ、最初のループの 'files.append(dest)')。 – spectras

+1

サイドノートとして、2番目のループで 'f'を決して閉じることはありません。あなたのディレクトリにたくさんのファイルがある場合、それは壊れます。 – spectras

答えて

0
files = glob.glob(path) 
for file in files: # starting to scan the files 
    with open(file, 'r') as f 
     lines = f.read() 
     output = re.search(r'error', lines) # regexp to search for 'error' 
     if output: 
      query = """INSERT INTO import (Fehler,Filename) VALUES ("1","%s")""" 
       x.execute(query, file) # insert error to db 
       db.commit() 
    os.remove(file) # remove file 
関連する問題