Python 搜索作为输入提供的文件目录?

Python 搜索作为输入提供的文件目录?,python,Python,因此,我被分配了一项任务,从用户那里获取3个参数,然后执行以下任务: 搜索作为输入给定的文件夹。 查找所有特定文件类型扩展名。 将此文件打印到其他文件夹 有没有更简单的方法来执行此任务?尝试使用os.listdir时,会响应找不到该文件,因为它不接受变量作为输入 Directories = []; InitDirect = str(input('Please insert the file directory you want to search (C:\\x)')) FileType = s

因此,我被分配了一项任务,从用户那里获取3个参数,然后执行以下任务:

搜索作为输入给定的文件夹。 查找所有特定文件类型扩展名。 将此文件打印到其他文件夹

有没有更简单的方法来执行此任务?尝试使用os.listdir时,会响应找不到该文件,因为它不接受变量作为输入

Directories = [];
InitDirect = str(input('Please insert the file directory you want to search (C:\\x)'))

FileType = str(input('Please state a desired file type (.txt, .png)'))

OutDirect = str(input('Please state the output directory for the files.'))

for file in os.listdir("InitDirect"):
    if file.endswith("FileType"):
        print(os.path.join("InitDirect", file))

这是我当前的代码,尽管可能不正确。如果有人能帮忙,那太好了

变量名周围不需要使用引号。在变量名周围添加“”实际上声明了字符串,并且您没有使用变量的值。将代码更改为以下内容,它应该可以工作

Directories = [];
InitDirect = str(input('Please insert the file directory you want to search (C:\\x)'))

FileType = str(input('Please state a desired file type (.txt, .png)'))

OutDirect = str(input('Please state the output directory for the files.'))

for file in os.listdir(InitDirect):
    if file.endswith(FileType):
        print(os.path.join(InitDirect, file))

从最后3行中删除所有rhe/“自”“谢谢你!这确实帮助我解决了问题。这是否有可能将文件打印到另一个文件夹,或者需要一组不同的代码?当您说打印文件时,您指的是文件的内容还是文件名?如果要打印文件内容,需要使用“打开并读取”。看看这里->谢谢!我会通读一遍,找出解决办法。你帮了我大忙,非常欢迎。如果我的答案对您有帮助,请单击绿色复选标记接受它好吗?