簡體   English   中英

合並 python 中的兩個文件夾

[英]Merge two folders in python

我需要合並兩個文件夾,

文件夾命名為 12345 和 12345_

我將如何合並兩者?

我試過了,但我最終得到了“12345”。

for file in files:
    subFolder = os.path.join(destpath, file[:6])
    if not os.path.isdir(subFolder):
        os.makedirs(subFolder)
    shutil.copy(os.path.join(root, file), subFolder)

我需要合並兩個文件夾,

這些文件夾分別命名為12345和12345_

我將如何合並兩者?

我已經嘗試過,但最終得到的是“ 12345”。

for file in files:
    subFolder = os.path.join(destpath, file[:6])
    if not os.path.isdir(subFolder):
        os.makedirs(subFolder)
    shutil.copy(os.path.join(root, file), subFolder)

我需要合並兩個文件夾,

這些文件夾分別命名為12345和12345_

我將如何合並兩者?

我已經嘗試過,但最終得到的是“ 12345”。

for file in files:
    subFolder = os.path.join(destpath, file[:6])
    if not os.path.isdir(subFolder):
        os.makedirs(subFolder)
    shutil.copy(os.path.join(root, file), subFolder)

我用純 python 編寫了一個簡單的遞歸函數,它不調用任何 shell 命令。 在此示例中,folder1 的所有內容(文件和目錄)都將合並到 folder2:

import os
import shutil

def merge(scr_path, dir_path):
  files = next(os.walk(scr_path))[2]
  folders = next(os.walk(scr_path))[1]
  for file in files: # Copy the files
    scr_file = scr_path + "/" + file
    dir_file = dir_path + "/" + file
    if os.path.exists(dir_file): # Delete the old files if already exist
      os.remove(dir_file)
    shutil.copy(scr_file, dir_file)
  for folder in folders: # Merge again with the subdirectories
    scr_folder = scr_path + "/" + folder
    dir_folder = dir_path + "/" + folder
    if not os.path.exists(dir_folder): # Create the subdirectories if dont already exist
      os.mkdir(dir_folder)
    merge(scr_folder, dir_folder)

path1 = "path/to/folder1"
path2 = "path/to/folder2"

merge(path1, path2)

如果替換目標目錄中的文件(如果它們已經存在)是可以接受的,那么從 Python 3.8 開始,這可以通過shutil.copytree輕松實現;

import shutil
shutil.copytree("src_root", "dst", dirs_exist_ok=True)

這里的文檔:

遞歸復制以 src 為根的整個目錄樹到名為 dst 的目錄並返回目標目錄。 默認情況下,還將創建包含 dst 所需的所有中間目錄。

如果 dirs_exist_ok 為 false(默認值)並且 dst 已經存在,則會引發 FileExistsError。 如果 dirs_exist_ok 為 true,則如果遇到現有目錄,復制操作將繼續,並且 dst 樹中的文件將被 src 樹中的相應文件覆蓋。

3.8 版新功能:dirs_exist_ok 參數。

寫入Excel工作表的這個選項怎么樣?

import xlsxwriter


# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('C:/Users/your_path_here/Excel_File.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)

# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})

# Write some simple text.
worksheet.write('A1', 'Hello')

# Text with formatting.
worksheet.write('A2', 'World', bold)

# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)


workbook.close()

暫無
暫無

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

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