如何用if条件检查目录内指定格式当日文件存在性?代码求助
Hey there! Let's dig into why your file check isn't picking up the existing files even when they're right there. Here are the most common issues to investigate step by step:
First off, double-check that your presentday variable's output exactly matches the date segment in your target filenames. For example, if your file is named OIS_GCU.20180310012345, your presentday should generate 20180310 (YYYYMMDD) — not 2018-03-10, 10-03-2018, or a string with extra time values.
- Add a quick print statement to verify:
Compare this output directly to the date part in your actual filename to catch any discrepancies.print(f"Expected date pattern: {presentday}")
- Are you using a relative path? If your code runs from a different working directory than where the files are stored, it'll look in the wrong place. Print the full absolute path you're checking to confirm:
import os target_dir = "./your-target-dir" print(f"Checking directory: {os.path.abspath(target_dir)}") - Also, make sure the user running your code has read permissions for that directory. On Linux/macOS, restricted permissions can silently hide files from your script.
Your pattern might be too strict or incorrectly formatted. Since filenames end with random digits after the date, you need to use a wildcard to account for that extra text:
- If you're using Python's
globmodule, the correct pattern should look like this:import glob matching_pattern = f"OIS_GCU.{presentday}*" matching_files = glob.glob(os.path.join(target_dir, matching_pattern)) - Don't forget about case sensitivity! If your code uses lowercase
ois_gcubut the actual files have uppercaseOIS_GCU, this will fail on Linux/macOS (though Windows is case-insensitive).
Sometimes a file might be in the process of being written to disk when your code checks for it. The OS might not have fully flushed the file to the filesystem yet. Try adding a short delay before checking:
import time time.sleep(1) # Wait 1 second for file to finish writing
Also, ensure no other process has locked the file (like a text editor or upload tool) — locked files can sometimes be invisible to directory scans.
Double-check your if condition itself. It's easy to accidentally invert the logic, like writing if not matching_files: instead of if matching_files:. Or maybe you're adding extra checks (like file size or modification time) that aren't being met, even though the file exists.
Start by printing out the list of matched files (print(matching_files)). If it's empty, you know the issue is in the pattern/path/date. If it's not empty but the code still hits else, then your if condition is the problem.
内容的提问来源于stack exchange,提问作者RayArts

