【问题标题】:Python File Detection LoopPython 文件检测循环
【发布时间】: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)。

【问题讨论】:

标签: python linux for-loop while-loop directory


【解决方案1】:

最简单的解决方案可能是创建一个函数来使用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

【讨论】:

  • 约翰尼,成功了,感谢您的帮助!
  • 现在我已经完成了一些测试(运行完美),我发现我有错误。当我将文件放在需要运行脚本的目录中时,它不起作用。它告诉我没有这样的文件或目录'CustomerInfo.txt',实际上有。我可能需要尝试将 dir_path 更改为指向我希望脚本运行的绝对路径。
【解决方案2】:

我已经使用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')

【讨论】:

  • Faraaz,我得试一试,看看它是否能正常运行。谢谢!
  • 这也完全符合我的要求,感谢分享您的代码!
  • @jmashburn ,很高兴能帮到你。
猜你喜欢
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 2014-04-08
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多