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

如何不使用subprocess模块用Python实现文件筛选、名称处理及保存

Ditch the Subprocess: Pure Python Solution for Your File Task

Hey there! Instead of relying on shell commands via subprocess, you can use Python's built-in file system modules to get the same result—no external calls needed, and it's more cross-platform friendly too. Here are two clean approaches:

Modern Approach with pathlib (Python 3.4+)

pathlib is the recommended way to handle file paths in modern Python. It's intuitive and object-oriented:

from pathlib import Path

# Set up your directory and output file paths
target_dir = Path("/root/test/")
output_path = target_dir / "testlist.txt"

# Find all files ending with .uwsgi.log (skip directories)
uwsgi_logs = [file for file in target_dir.glob("*.uwsgi.log") if file.is_file()]

# Strip the .uwsgi.log suffix from each filename
clean_names = [file.name[:-len(".uwsgi.log")] for file in uwsgi_logs]

# Write the result to your output file
# Use "\n".join for one name per line (matches shell command behavior)
# Use " ".join if you want space-separated names like your example output
with open(output_path, "w") as f:
    f.write("\n".join(clean_names))

Breakdown:

  • Path("/root/test/") creates a path object that handles directory paths cleanly.
  • glob("*.uwsgi.log") searches for all files matching the exact suffix pattern.
  • We add if file.is_file() to avoid accidentally including directories with the same name.
  • file.name[:-len(".uwsgi.log")] removes the fixed suffix from each filename (since we know the exact length of the suffix we want to strip).

Traditional Approach with os Module

If you're more familiar with the older os module, this works too:

import os

target_dir = "/root/test/"
output_path = os.path.join(target_dir, "testlist.txt")

# Get all entries in the directory, filter for files ending with .uwsgi.log
all_entries = os.listdir(target_dir)
uwsgi_logs = [
    filename for filename in all_entries
    if os.path.isfile(os.path.join(target_dir, filename))
    and filename.endswith(".uwsgi.log")
]

# Strip the suffix
clean_names = [filename[:-len(".uwsgi.log")] for filename in uwsgi_logs]

# Write to output file
with open(output_path, "w") as f:
    f.write("\n".join(clean_names))

Why This Is Better Than subprocess:

  • Cross-platform: Works on Windows, macOS, and Linux without changing code (your shell command is Unix-only).
  • Error handling: You can easily add try/except blocks to handle missing directories, permission issues, etc.
  • Readability: The code clearly shows what you're doing, instead of relying on shell pipeline syntax that might be harder to debug.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:34:39