gpt4 book ai didi

python - 使用 glob() 获取自定义目录中的文件列表

转载 作者:太空宇宙 更新时间:2023-11-03 11:35:52 24 4
gpt4 key购买 nike

我正在尝试编写一个程序,在用户输入自己的自定义文件目录时重命名文件。我还处于很早的阶段。这是我第一次使用 OS 和 glob 命令。我的代码如下。但是,当我尝试运行它时,结果是一个空列表。我尝试直接在 glob 命令中输入一个文件根目录,它以某种方式工作,但结果不是我想要的。

希望大家帮帮我。谢谢。

import os, globdef fileDirectory():    #Asks the user for a file root directory    fileroot = raw_input("Please input the file root directory \n\n")

#Returns a list with all the files inside the file root directory
filelist = glob.glob(fileroot)
print filelist

文件目录()

最佳答案

Python 对空格敏感,因此您需要确保函数内的所有内容都已缩进。

Stackoverflow 对代码有自己的缩进要求,这使得很难确定您的代码最初的缩进是什么。

import os, glob
def fileDirectory():
#Asks the user for a file root directory
fileroot = raw_input("Please input the file root directory \n\n")

#Returns a list with all the files inside the file root directory
filelist = glob.glob(fileroot)
print filelist
fileDirectory()

接下来是 glob 返回 glob 的结果 - 它没有列出目录,这似乎是您正在尝试做的。

要么你想要 os.listdir,要么 os.walk 或者你实际上应该要求一个 glob 表达式而不是一个目录。

最后,raw_input 可能会给您一些额外的空白,您必须将其去除。检查文件根目录是什么。

您可能想要拆分您的程序,以便您可以分别研究每个函数。

关于python - 使用 glob() 获取自定义目录中的文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3429584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com