簡體   English   中英

Python 與文件夾和文件夾內的文件相關的問題

[英]Python Question Related to Folders and Files inside of the folders

我有一個包含蘋果和橙色圖像的文件夾(水果)。 假設每個人五十個。 該文件夾包含總共 100 張圖像。

在這個水果文件夾中,Apple 圖像被保存為apple0.jpg, apple1.jpg........ apple49.jpg

另一方面,橙色圖像的保存方式為orange0.jpg, orange1.jpg, orange2.jpg........ orange49.jpg

因此,使用這些數據,我如何創建一個 Apple 文件並將所有蘋果圖像復制到那里。 不僅如此,我如何創建橙色文件並將所有橙色圖像復制到該橙色文件。

我正在使用 Python 編程語言。 有沒有關於這個的教程,或者你知道我該怎么做。

感謝您的所有評論。 我打算在 Google colab 中做這些。

假設您的意思是要創建一個新文件夾 Apples and Oranges 來移動文件,如果可以依賴文件以 apple 或 oranges 開頭,則可以使用以下簡單的粗暴代碼:-

import os
import shutil

files = os.listdir('Fruits')

if not os.path.isdir('Oranges'):
  os.mkdirs('Oranges')

if not os.path.isdir('Apples'):
  os.mkdirs('Apples')

for f in files:
  if not f.endswith('.jpg'):
    continue
  
  if f.startswith('apple'):
    target = os.path.join('Apples', f)
  elif f.startswith('orange'):
    target = os.path.join('Oranges', f)
   
  shutil.move(os.path.join('Fruits', f), target)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM