如何用Python代码在Jupyter Notebook选择最新.txt运行及异常排查
Hey there! Let's work through your two questions to get this sorted out.
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:
pathlibsimplifies file path handling and lets us easily find all.txtfiles 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
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.pyisn't built to handle multiple files (or processes them in an unordered way), adding a new file could trigger parsing errors - The new
.txtfile 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

