【问题标题】:Counting files normally within a directory using Python使用 Python 对目录中的文件进行计数
【发布时间】:2021-12-04 16:03:02
【问题描述】:

我正在遍历 HTML 文件目录并尝试按升序打印文件名。人类通常会计算它们的方式。


我想要的输出:

目录中的文件 9:

上一个视频是08--PL4OFZnQ3wLGlJ7_SioKhwvsckGY0ZENSh&FKgTxV_W39Y.html

下一个视频是10--PL4OFZnQ3wLGlJ7_SioKhwvsckGY0ZENSh&HvsE0284W3g.html

目录中的文件 10:

上一个视频是09--PL4OFZnQ3wLGlJ7_SioKhwvsckGY0ZENSh&8jhh21EFlqg.html

下一个视频是11--PL4OFZnQ3wLGlJ7_SioKhwvsckGY0ZENSh&gSAfguVusZU.html

...

目录中的文件 12:

上一个视频是11--PL4OFZnQ3wLGlJ7_SioKhwvsckGY0ZENSh&gSAfguVusZU.html

下一个视频是13--PL4OFZnQ3wLGlJ7_SioKhwvsckGY0ZENSh&JAx5IvBvHyA.html

等等等等。


我的代码适用于少于 100 个 HTML 文件的目录,我得到了所需的输出。但是对于超过 100 个 HTML 文件的目录,计数会被破坏。


这是我的代码。 对不起如果它看起来像意大利面条,它不是最漂亮的代码:

for index, file in enumerate(iterable_directory):

    # Ignore any 'index.html' file in the video directories
    if file.startswith("index"):
        continue

    # See if there are only 2 files present in directory
    if len(iterable_directory) == 2:
        prev_video = '#'
        next_video = '#'
        print(f'At file {index+1} in the directory:\n')
        print(f'The prev vid is {prev_video}\nThe next vid is {next_video}\n')

        continue
    else:                        
        # Grab the first and last html file in each playlist directory
        first_item = iterable_directory[0]
        last_item = iterable_directory[-2]

        # Check if the file is an html file and ignore it if it is an 'index.html' file.
        # Then, check if the file is the first or last file in the directory.
        if file.endswith(".html") and file != "index.html":
            if file == first_item:
                prev_video = '#'
                next_video = f"{iterable_directory[1]}"

                print(f'At file {index+1} in the directory:\n')
                print(f'The prev vid is {prev_video}\nThe next vid is {next_video}\n')

                continue
            elif file == last_item:
                prev_video = f"{iterable_directory[-3]}"
                next_video = '#'

                print(f'At file {index+1} in the directory:\n')
                print(f'The prev vid is {prev_video}\nThe next vid is {next_video}\n')

                continue
            elif (index + 1 < len(iterable_directory) and index - 1 >= 0):
                prev_video = str(iterable_directory[index-1])
                next_video = str(iterable_directory[index+1])

                print(f'At file {index+1} in the directory:\n')
                print(f'The prev vid is {prev_video}\nThe next vid is {next_video}\n')

                continue

这个带有 sorted 函数的 lambda 函数确实按照我想要的顺序对文件进行排序,但我似乎仍然无法弄清楚如何将它放入我的代码中以使其工作。

sorted(iterable_directory, key=lambda x: int(x.split(os.path.sep)[-1].split('-')[0]) if x!="index.html" else 0)

我会非常感谢任何帮助,我已经做了一个星期了,我一直为此失眠。提前谢谢!

【问题讨论】:

    标签: python loops sorting lambda counting


    【解决方案1】:

    我认为这应该可以满足您的需求:

    import glob
    import os
    
    HOME = os.path.expanduser('~')
    BASEDIR = os.path.join(HOME, 'html') # The directory containing the html files
    
    def getfilelist():
        filelist = []
        for htmlfile in glob.glob(os.path.join(BASEDIR, '*.html')):
            base = os.path.basename(htmlfile)
            if not base.startswith('index'):
                filelist.append(base)
        return sorted(filelist)
    
    
    def main():
        filelist = getfilelist()
        for i, _ in enumerate(filelist[1:-1], 1):
            print(f'At file {i} in the directory\n')
            print(f'The prev vid is {filelist[i-1]}')
            print(f'The next vid is {filelist[i+1]}\n')
    
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      • 2019-01-16
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 2011-02-17
      相关资源
      最近更新 更多