如何在Python中使用glob库定位文件并打印它们

huangapple go评论64阅读模式
英文:

How do I locate files with glob lib in Python and print them

问题

请告诉我这里有什么问题,我已经在互联网上查了3天,找不到解决方案。

import pandas as pd
import os
import glob

folder_name = input("请输入要定位数据库的文件夹名称:")
diskD = glob.glob(f"D:/*/{folder_name}/*.*", recursive=True)
inFilesD = glob.glob(diskD)
print(os.path.basename(inFilesD))

我尝试更改了多行代码,希望程序能够定位特定文件夹并打印出其内容/文件。

英文:

Please tell me what is wrong here, I've been digging the internet over 3 days and can't find the solution.

import pandas as pd
import os
import glob

folder_name = input("Please insert the folder name to locate databases: ")
diskD = glob.glob("D:/*/{folder_name}/*.*".format, root_dir="D:", dir_fd=1, recursive=True)
inFilesD = glob.glob(diskD)
print(os.path.basename(inFilesD))

I tried changing multiple lines, HOPING for program to locate a specific folder and print out it's content/files

答案1

得分: 1

使用f-string来格式化路径名。使用**来搜索所有文件夹。

不需要两次调用glob.glob(),第一个调用已经返回了所有文件名。

遍历所有结果,在每个结果上调用os.path.basename();不能直接在列表上调用它。

folder_name = input("请输入要定位数据库的文件夹名称:")
diskD = glob.glob(f"D:/**/{folder_name}/*.*", recursive=True)
for file in diskD:
    print(os.path.basename(file))
英文:

Use an f-string to format the pathname. Use ** for the directory to search all folders.

There's no need to call glob.glob() twice, the first one already returned all the filenames.

Loop over all the results, calling os.path.basename() on each of them; you can't call it on the list directly.

folder_name = input("Please insert the folder name to locate databases: ")
diskD = glob.glob(f"D:/**/{folder_name}/*.*", recursive=True)
for file in diskD:
    print(os.path.basename(file))

huangapple
  • 本文由 发表于 2023年3月4日 03:57:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定