【问题标题】:Python glob does not find any resultsPython glob 没有找到任何结果
【发布时间】:2021-01-10 21:43:16
【问题描述】:

我正在尝试从文本文件中提取一些数据。 这些是代码行:

directory = './mydirec'
files = glob('{0:s}/*.gather.txt'.format(directory))

我一直收到 [] ,所以没有结果。有人可以帮我理解为什么吗? 谢谢

【问题讨论】:

  • 尝试使用完整路径。或者确保您从正确的目录运行 (os.getcwd().
  • 您期望的输出是什么?此目录中有哪些文件/路径?
  • 如果mydirec 与脚本在同一个目录中,请执行directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mydirec')
  • 只是一个猜测:也许尝试'.'而不是'./mydirec'

标签: python file glob fnmatch


【解决方案1】:

也许我误解了你的问题,但是从 .txt 中收集数据真的很容易。您可以使用 3 或 4 行代码打开和读取文本文件:

f = open("file.txt", "r+")
data = f.read()
print(data)
f.close()

如果您要从 .txt 的特定行中查找数据,您可以使用:

f = open("file.txt", "r+")
lines = f.readlines()
print(lines[25])
f.close()

或者如果您想在一般的文本文件中查找特定的数据

f = open("file.txt", "r+")
read = f.read()
data = read
f.close()
if "<specific word you're looking for>" in data:
#react based on the information being in the data.

我认为您不必弄乱 .format 或类似的东西,您可以使用文件的路径,或者如果它与您的脚本在同一个文件夹中,只需使用文件名。

【讨论】:

  • 我认为问题在于为什么glob() 没有产生预期的输出
  • 那是我的错。我读到“试图从文件中获取数据”和“这段代码不起作用”,然后就像“但是你为什么要这样做呢?阅读文本文件很容易,只要这样做。”
  • 标题确实具有误导性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-27
  • 1970-01-01
  • 2018-08-31
  • 1970-01-01
相关资源
最近更新 更多