Python 文件检测循环
Python File Detection Loop
我正在尝试创建一个 Python 脚本来循环遍历目录中的所有文件,当它检测到以 TestFile 开头的文件时,我希望循环停止.我目前的尝试是在找到文件后导致循环继续,或者在目录循环一次后结束脚本。如有任何帮助,我们将不胜感激。
import os
import time
# Defining variables
dir_path = os.path.dirname(os.path.realpath(__file__))
timeout = 30 # seconds
timeoutStart = time.time()
# While loop that should last 15 minutes
# to search for any file that starts with
# CustomerInfo, then the loop breaks when
# a file is found.
while time.time() < timeoutStart + timeout:
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.startswith('TestFile'):
file_export = root+'\'+str(file)
file_name = file
print(file_export)
print(file_name)
break
更新代码后我现在遇到的错误:
Traceback (most recent call last):
File "/script/dir/FileTransfer.py", line 80, in <module>
if find_file(dir_path, 'TestFile'):
File "/script/dir/FileTransfer.py", line 26, in find_file
send_email('<my email address>',
File "/script/dir/FileTransfer.py", line 53, in send_email
attachment = open(attachment_location, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'TestFile.txt'
注意:当我从我的用户目录 运行 下载脚本时,该脚本可以工作,但是当我将文件移动到我需要脚本的位置时,它就不起作用 运行。
已更新完整脚本:
#!/usr/bin/env python3
import os
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path
# Defining variables
dir_path = os.path.dirname(os.path.realpath(__file__))
timeout = 900 # seconds
timeoutStart = time.time()
# Creating a function that loops through
# the directory searching for the file.
def find_file(dir_path, txt):
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.startswith(txt):
print(os.path.join(root, file))
print(file)
send_email('<my email address',
'<subject>',
'<body>',
file_export)
return True
return False
# Creating a function that sends an email along
# with attaching the file found by the find_file
# function noted above.
def send_email(email_recipient,
email_subject,
email_message,
attachment_location=''):
email_sender = '<my email address>'
msg = MIMEMultipart()
msg['From'] = email_sender
msg['To'] = email_recipient
msg['Subject'] = email_subject
msg.attach(MIMEText(email_message, 'plain'))
if attachment_location != '':
filename = os.path.basename(attachment_location)
attachment = open(attachment_location, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
"attachment; filename= %s" % filename)
msg.attach(part)
try:
server = smtplib.SMTP('<email server>', <port>)
server.ehlo()
server.starttls()
server.login('<server auth username>', '<server auth password>')
text = msg.as_string()
server.sendmail(email_sender, email_recipient, text)
print('email sent')
server.quit()
except:
print("SMTP server connection error")
return True
# While loop that should last 15 minutes
# to search for any file that starts with
# CustomerInfo, then the loop breaks when
# a file is found.
while time.time() < timeoutStart + timeout:
if find_file(dir_path, 'TestFile'):
break
# Print statement for log output.
print(time.time())
print("End of script.")
我找到了我的问题,我把上面的代码反映给有兴趣的人。电子邮件功能需要文件的绝对路径,我在这里只调用文件名(IE:在send_email函数下attachment_location被设置为文件而不是file_export)。
最简单的解决方案可能是创建一个函数来执行搜索,使用 return
在找到文件时终止该函数:
# Returns True only if the file is found
def find_file(dir_path, txt):
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.startswith(txt):
print(os.path.join(root, file))
print(file)
return True
return False
while time.time() < timeoutStart + timeout:
if find_file(dir_path, 'TestFile'):
break
我已经使用 datetime
模块获取当前时间并向其添加 15 分钟,如果完成 15 分钟则程序停止。
import os
import datetime
# Defining variables
dir_path = os.path.dirname(os.path.realpath(__file__))
start=datetime.datetime.now()
print(start)
total_time=start + datetime.timedelta(minutes = 0.5)
print(total_time)
# While loop that should last 15 minutes
# to search for any file that starts with
# CustomerInfo, then the loop breaks when
# a file is found.
stop_index=0
while start < total_time:
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.startswith('TestFile'):
file_export = root+'\'+str(file)
file_name = file
print(file_export)
print(file_name)
stop_index+=1
result.append('file found')
break
start=datetime.datetime.now()
if stop_index>0:
break
if stop_index>0:
break
if stop_index==0:
print('no file found')
我正在尝试创建一个 Python 脚本来循环遍历目录中的所有文件,当它检测到以 TestFile 开头的文件时,我希望循环停止.我目前的尝试是在找到文件后导致循环继续,或者在目录循环一次后结束脚本。如有任何帮助,我们将不胜感激。
import os
import time
# Defining variables
dir_path = os.path.dirname(os.path.realpath(__file__))
timeout = 30 # seconds
timeoutStart = time.time()
# While loop that should last 15 minutes
# to search for any file that starts with
# CustomerInfo, then the loop breaks when
# a file is found.
while time.time() < timeoutStart + timeout:
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.startswith('TestFile'):
file_export = root+'\'+str(file)
file_name = file
print(file_export)
print(file_name)
break
更新代码后我现在遇到的错误:
Traceback (most recent call last):
File "/script/dir/FileTransfer.py", line 80, in <module>
if find_file(dir_path, 'TestFile'):
File "/script/dir/FileTransfer.py", line 26, in find_file
send_email('<my email address>',
File "/script/dir/FileTransfer.py", line 53, in send_email
attachment = open(attachment_location, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'TestFile.txt'
注意:当我从我的用户目录 运行 下载脚本时,该脚本可以工作,但是当我将文件移动到我需要脚本的位置时,它就不起作用 运行。
已更新完整脚本:
#!/usr/bin/env python3
import os
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path
# Defining variables
dir_path = os.path.dirname(os.path.realpath(__file__))
timeout = 900 # seconds
timeoutStart = time.time()
# Creating a function that loops through
# the directory searching for the file.
def find_file(dir_path, txt):
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.startswith(txt):
print(os.path.join(root, file))
print(file)
send_email('<my email address',
'<subject>',
'<body>',
file_export)
return True
return False
# Creating a function that sends an email along
# with attaching the file found by the find_file
# function noted above.
def send_email(email_recipient,
email_subject,
email_message,
attachment_location=''):
email_sender = '<my email address>'
msg = MIMEMultipart()
msg['From'] = email_sender
msg['To'] = email_recipient
msg['Subject'] = email_subject
msg.attach(MIMEText(email_message, 'plain'))
if attachment_location != '':
filename = os.path.basename(attachment_location)
attachment = open(attachment_location, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
"attachment; filename= %s" % filename)
msg.attach(part)
try:
server = smtplib.SMTP('<email server>', <port>)
server.ehlo()
server.starttls()
server.login('<server auth username>', '<server auth password>')
text = msg.as_string()
server.sendmail(email_sender, email_recipient, text)
print('email sent')
server.quit()
except:
print("SMTP server connection error")
return True
# While loop that should last 15 minutes
# to search for any file that starts with
# CustomerInfo, then the loop breaks when
# a file is found.
while time.time() < timeoutStart + timeout:
if find_file(dir_path, 'TestFile'):
break
# Print statement for log output.
print(time.time())
print("End of script.")
我找到了我的问题,我把上面的代码反映给有兴趣的人。电子邮件功能需要文件的绝对路径,我在这里只调用文件名(IE:在send_email函数下attachment_location被设置为文件而不是file_export)。
最简单的解决方案可能是创建一个函数来执行搜索,使用 return
在找到文件时终止该函数:
# Returns True only if the file is found
def find_file(dir_path, txt):
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.startswith(txt):
print(os.path.join(root, file))
print(file)
return True
return False
while time.time() < timeoutStart + timeout:
if find_file(dir_path, 'TestFile'):
break
我已经使用 datetime
模块获取当前时间并向其添加 15 分钟,如果完成 15 分钟则程序停止。
import os
import datetime
# Defining variables
dir_path = os.path.dirname(os.path.realpath(__file__))
start=datetime.datetime.now()
print(start)
total_time=start + datetime.timedelta(minutes = 0.5)
print(total_time)
# While loop that should last 15 minutes
# to search for any file that starts with
# CustomerInfo, then the loop breaks when
# a file is found.
stop_index=0
while start < total_time:
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.startswith('TestFile'):
file_export = root+'\'+str(file)
file_name = file
print(file_export)
print(file_name)
stop_index+=1
result.append('file found')
break
start=datetime.datetime.now()
if stop_index>0:
break
if stop_index>0:
break
if stop_index==0:
print('no file found')