Python 脚本运行一天,但第二天不运行 [duplicate]

Python script runs one day, but not the next [duplicate]

提问人:Roelof 提问时间:11/13/2023 最后编辑:Roelof 更新时间:11/13/2023 访问量:50

问:

我正在尝试学习 Python,并且我已经能够创建一些实际有效的脚本。但是,我一直遇到的一个主要问题是几个脚本显然在运行,但立即再次关闭,不执行任何操作,并且不给出错误消息。我尝试添加诊断、检查权限、在任何地方拼写错误、路径、通过 ChatGPT 运行问题、查看本网站上的答案,我似乎找不到问题所在。这是代码:

import os
from datetime import datetime, timedelta

# Define your starting scan and source folder
start_name = "188307_00000563"
start_date = "18830706"
source_folder = "C:\\Users\\boeo\\1883 - kopie"

# Function call
rename_scans(start_name, start_date, source_folder)

# Function definition
def rename_scans(start_name, start_date, source_folder):
    current_name = start_name
    current_date = datetime.strptime(start_date, "%Y%m%d")
    page_number = 1

    while True:
        source_path = os.path.join(source_folder, f"{current_name}.jpg")
        if not os.path.exists(source_path):
            break

        new_name = current_date.strftime("%Y%m%d") + f".{page_number:02}"
        destination_path = os.path.join(source_folder, f"{new_name}.jpg")

        try:
            os.rename(source_path, destination_path)
            print(f"Renamed '{source_path}' to '{destination_path}'")
        except Exception as e:
            print(f"Failed to rename '{source_path}': {e}")

        page_number = 3 - page_number
        current_date += timedelta(weeks=1)
        current_name = current_date.strftime("%Y%m%d")

我尝试运行脚本,它打开了一个新窗口,但立即再次关闭,实际上什么也没做。它应该重命名文件,以便正确的日期在文件名中。

python 重命名

评论

3赞 Daviid 11/13/2023
打开脚本文件夹中的终端,然后从那里执行脚本,这样窗口就不会关闭。
0赞 tripleee 11/13/2023
您的系统上是否真的存在该目录?您确实应该提供足够的详细信息来排除明显和常见的初学者错误。source_folder
0赞 Roelof 11/13/2023
我直接从 Windows 资源管理器复制了该目录,因此名称应该是准确的,根据我之前找到的建议添加了额外的 \。
0赞 buran 11/13/2023
将函数调用移到函数定义之后
1赞 Amessihel 11/13/2023
标题让我想起了这个提交的错误。:)

答:

0赞 Christian 11/13/2023 #1

您在实现该方法之前使用了该方法,因此我假设您在运行该方法时总是遇到以下异常:rename_scans

Traceback (most recent call last):
  File "<<file>>.py", line 1, in <module>
    fun()
NameError: name 'rename_scans' is not defined

您必须将调用移到函数定义后面。 然后,按照建议,通过“python <file>.py”从控制台启动它更有帮助,因为您实际上会看到正在发生的事情的输出。