[英]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.