【问题标题】:Problem using glob: file not found after os.path.join()使用 glob 的问题:在 os.path.join() 之后找不到文件
【发布时间】:2021-12-31 09:19:08
【问题描述】:

我在使用 glob (python 3.10.0/Linux) 时遇到了奇怪的问题: 如果我使用 glob 使用以下构造来定位所需文件:

def get_last_file(folder, date=datetime.today().date()):
    os.chdir(folder)
    _files = glob.glob("*.csv")
    _files.sort(key=os.path.getctime)
    os.chdir(os.path.join("..", ".."))
    for _filename in _files[::-1]:
        string = str(date).split("-")
        if "".join(string) in _filename:
            return _filename
    # if cannot find the specific date, return newest file
    return _files[-1]

但是当我尝试时

os.path.join(fileDir, file)

使用生成的文件,我得到了导致的相对路径: FileNotFoundError:[Errno 2] 没有这样的文件或目录:'data/1109.csv'。 文件肯定存在,当我尝试 os.path.join(fileDir, '1109.csv') 时,找到了文件。 最奇怪的事情 - 如果我这样做:

filez = get_last_file(fileDir, datetime.today().date())
file = '1109.csv''

在 os.path.join(fileDir, file) 之后,我仍然找不到 file 的文件。

我应该完全避免使用 glob 吗?

【问题讨论】:

    标签: python-3.x glob


    【解决方案1】:

    我做了这样的解决方案:

    file =''
    _mtime=0
    for root, dirs, filenames in os.walk(fileDir):
       for f in sorted(filenames):
          if f.endswith(".csv"):
             if os.path.getmtime(fileDir+f) > _mtime:
                _mtime = os.path.getmtime(fileDir+f)
                file = f
    print (f'fails {file}')
    

    得到的 os.path.join(fileDir, file) 给出了适合进一步操作的(相对)路径 还考虑了 getctime 和 getmtime 之间的差异。

    【讨论】:

      【解决方案2】:

      虽然不是直接的解决方案,但请尝试查看 Python 的 Pathlib 库。它通常会带来更清洁、错误更少的解决方案。

      from pathlib import Path
      def get_last_file(folder, date=datetime.today().date()):
          folder = pathlib.Path(folder) # Works for both relative and absolute paths
          _files = Path.cwd().glob("*.csv")
          _files.sort(key=os.path.getctime)
          grandparent_path = folder.parents[1]
          for _filename in _files[::-1]:
              string = str(date).split("-")
              if "".join(string) in _filename:
                  return _filename
          # if cannot find the specific date, return newest file
          return _files[-1]
      

      然后,您可以使用path_dir / file_name 而不是使用os.path.join(),其中path_dirPath 对象。这也可能是您正在更改函数中的基本路径,从而导致意外行为的情况。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-29
        • 2022-01-06
        相关资源
        最近更新 更多