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

Python脚本添加排除文件判断后失效,含or语句时无法运行求助

问题分析与解决

你的代码核心问题出在条件判断的逻辑错误上:

if file == 'main.py' or 'Password.txt':

这行代码的实际执行逻辑是 (file == 'main.py') or ('Password.txt'),而非空字符串在Python的布尔判断中会被视为True,所以不管当前file是什么值,这个条件永远为True,导致所有文件都被pass跳过,自然不会执行写入操作。

正确的写法

你需要明确对file进行两次相等判断,或者用in关键字检查文件是否在目标列表中:

写法一:明确的多条件判断

import os

def main():
    for file in os.listdir():
        if file == 'main.py' or file == 'Password.txt':
            pass
        else:
            try:
                with open(file, 'a') as f:
                    f.write("hello")
                    print(f"{file}: success")
            except Exception as e:
                print(f"{file}: error - {str(e)}")

main()

写法二:用in简化判断(更推荐)

import os

def main():
    skip_files = {'main.py', 'Password.txt'}
    for file in os.listdir():
        if file in skip_files:
            continue
        try:
            with open(file, 'a') as f:
                f.write("hello")
                print(f"{file}: success")
        except Exception as e:
            print(f"{file}: error - {str(e)}")

main()

额外优化点

  • 把with open里的变量名从file改为f,避免和循环变量file同名造成混淆
  • 捕获具体的Exception并打印错误信息,方便排查文件无法写入的原因
  • 打印时带上文件名,能清晰看到每个文件的处理状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:35:21