如何在python中获取以数字结尾的文件夹名称

2024-10-03 11:13:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的文件夹

post
-----1
------10am
-----------images
-----2
-------10am
-----------images
-----3
------10am
-----------images

此文件夹最多31个,具有相同的子文件夹“10am”,其中有另一个文件夹“images”

在另一个文件夹中,根据python中的文件夹名称,我有需要复制的所有图像和.txt文件 files inside another folder

所以我现在需要做的是复制 “post\2\10am\images”中的“2.jpg”和 “post\2\10am”中的“2.txt”等

以下是我目前的代码:

import os,shutil

sampleFiles = r"\practice image and text"
destination = r"\posts"
time = '10am'

sample = os.listdir(sampleFiles)
#  sample = ['10.jpg', '10.txt', '11.jpg', '11.txt', '13.png', '13.txt', '16.jpg', '16.txt', '17.jpg', '17.txt', '18.jpg', '18.txt', '2.jpg', '2.txt', '20.jpg', '20.txt', '23.jpg', '23.txt', '24.jpg', '24.txt', '25.jpg', '25.txt', '27.jpg', '27.txt', '3.jpg', '3.txt','4.jpg', '4.txt', '5.jpg', '5.txt', '6.jpg', '6.txt', '9.jpg', '9.txt']


for root, dirs, files in os.walk(destination):
  for folderName in dirs:
  #get root + foldername
  rootWithFolder = os.path.join(root, folderName)

  #get path to date
  pathToDate = rootWithFolder.endswith(int(folderName)) # how to get the number?

  # get path to image folders
  if rootWithFolder.endswith('images'):
     pathToImage = rootWithFolder

  #copy .jpg files to pathToImage
  shutil.copy(sampleFiles + '\\' + str(pathToDate) + '.jpg'   , pathToImage) #not the most elegant way

  #copy .txt files to pathToDate
  shutil.copy(sampleFiles + '\\' + str(pathToDate) + '.txt'   , pathToDate + '\\' + 'time') #not the most elegant way

在我的代码中,我被困在如何获取pathToDate上,因此我可以根据文件夹的名称复制它

我试着像这样使用def

def allfiles(list):
 for i in range(len(list)):
  return list[i] # returns only the first value of the list
  # print(list[i]) #but this one returns all the value of the list

 allfiles(sample)

但它只返回列表的一个实例

我的问题是,如何获取名为number的文件夹并忽略strings之类的10am folderimages folder

还是有更好的方法?多谢各位


Tags: thetotxt文件夹getospostlist
1条回答
网友
1楼 · 发布于 2024-10-03 11:13:05

如果你还在寻找解决方案,这里有一个建议。。。我会反过来说:

from pathlib import Path
from shutil import copy

sample_folder = Path("practice image and text")
dest_folder = Path("posts")

for file in sample_folder.glob("*.*"):
    number, suffix = file.name.split(".")
    if suffix == "txt":
        copy(file, dest_folder / number / "10am")
    else:
        copy(file, dest_folder / number / "10am" / "images")

相关问题 更多 >