【发布时间】: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