You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python代码在Jupyter Notebook选择最新.txt运行及异常排查

Hey there! Let's work through your two questions to get this sorted out.

1. Python Code to Automatically Run the Newest .txt File in Jupyter Notebook

Instead of relying on shell wildcards that might cause unexpected issues, we can write a straightforward Python script to explicitly find and run the newest .txt file in your Results directory. Here's a reliable implementation:

from pathlib import Path
import subprocess

# Point to your target Results directory
results_folder = Path("Results")

# Fetch all .txt files, sort by last modified time (newest first), pick the top one
newest_txt_file = sorted(
    results_folder.glob("*.txt"),
    key=lambda file: file.stat().st_mtime,
    reverse=True
)[0]

# Build the command to run txt2pdf.py with the newest file
run_command = ["python", "txt2pdf.py", str(newest_txt_file)]

# Execute the command and capture output for debugging
execution_result = subprocess.run(run_command, capture_output=True, text=True)

# Print the output to see the process status
print("Output:\n", execution_result.stdout)
if execution_result.stderr:
    print("\nErrors encountered:\n", execution_result.stderr)

Quick breakdown:

  • pathlib simplifies file path handling and lets us easily find all .txt files in the directory
  • We sort files using st_mtime (last modified timestamp) to guarantee we always grab the latest file
  • subprocess.run() gives us full control over command execution, and we can capture both standard output and errors to debug any issues
2. Why run txt2pdf.py Results/*.txt Fails After New Files Are Created

When you run that command in Jupyter, the *.txt wildcard is expanded by the underlying shell. A few likely culprits for the broken u... output:

  • Jupyter's shell might cache the list of files, so it doesn't immediately recognize the newly created file
  • If txt2pdf.py isn't built to handle multiple files (or processes them in an unordered way), adding a new file could trigger parsing errors
  • The new .txt file might have encoding or formatting quirks that cause the script to fail when processing all files at once

The cleanest fix is the code above: by targeting only the newest file explicitly, you avoid wildcard ambiguity and ensure you're only processing the file you intended. No more unexpected behavior when new files are added!

内容的提问来源于stack exchange,提问作者Tyson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:59:32