有人挑战我创建一个程序,根据拍摄的月份将他们的照片分类到文件夹中,我想在一行中完成(我知道,它效率低且不可读,但我仍然想这样做,因为一个-衬里很酷)
我需要一个 for 循环来完成此操作,但我知道在一行中使用 for 循环的唯一方法是列表理解,这就是我所做的,但它会创建一个空列表,并且不会从列表中打印任何内容或任何东西。
我正在做的是将文件重命名为创建月份+原始文件名(例如bacon.jpg --> May\bacon.jpg
:)
这是我的代码(Python 3.7.3):
import time
import os.path
[os.rename(str(os.fspath(f)), str(time.ctime(os.path.getctime(str(os.fspath(f))))).split()[1] + '\\' + str(os.fspath(f))) for f in os.listdir() if f.endswith('.jpg')]
以及更具可读性的非列表理解版本:
import time
import os.path
for f in os.listdir():
fn = str(os.fspath(f))
dateCreated = str(time.ctime(os.path.getctime(fn)))
monthCreated = dateCreated.split()[1]
os.rename(fn, monthCreated + '\\' + fn)
列表理解是一种不好的方法吗?[]
另外,如果我打印列表而不是,是否有原因[None, None, None, None, None, (continuing "None"s for every image moved)]
?
请注意:我知道这是低效和不好的做法。如果我这样做的目的不仅仅是为了好玩,看看我是否能做到,我显然不会尝试在一行中做到这一点。