【发布时间】:2021-10-16 04:43:05
【问题描述】:
我正在尝试创建一个循环遍历目录中所有文件的 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.")
我发现了我的问题,并将上面的代码反映给感兴趣的人。 email函数需要文件的绝对路径,这里我只调用文件名(IE:send_email函数下的attachment_location设置为file而不是file_export)。
【问题讨论】:
-
看来这就是你要找的stackoverflow.com/questions/189645/…
标签: python linux for-loop while-loop directory