python代码求助移动文件组合问题。

查看 62|回复 4
作者:1e3e   
用python代码处理“G:\shangchang"的文件如下:
第一种情况:如果G:\shangchang大小小于3gb(含等于3gb),则新建G:\shangchang1文件夹,将G:\shangchang的所有文件移动到G:\shangchang1文件夹中。
第二种情况:如果G:\shangchang大小大于3gb(不含等于3gb),则将G:\shangchang中当前根目录的文件或一级子目录随机组合(组合可以是若干个随机文件的组合、若干个随机文件和若干个文件夹的组合、若干个随机文件夹的组合,注意若干个是大于等于0的整数),只要随机组合的大小大于3gb且小于4.9gb,就新建命名规则为G:\shangchang1、G:\shangchang2、………等文件夹,将上述随机组合移动到新建的上述的文件夹中。
目前的代码:
import os
import shutil
import random
from pathlib import Path
def get_dir_size(dir_path: Path) ->
int
:
    total = 0
[color=]   
for entry in dir_path.iterdir():
        if entry.is_file():
            total += entry.stat().st_size
        elif entry.is_dir():
            total += get_dir_size(entry)
    return total
def random_combination(dir_path: Path, min_size:
int
, max_size:
int
):
    files = [f for f in dir_path.iterdir() if f.is_file()]
    dirs = [d for d in dir_path.iterdir() if d.is_dir()]
    # Randomly choose files and/or directories until the combination size meets the criteria
    current_size = 0
[color=]   
combination = []
    while current_size or (max_size is not None and current_size > max_size):
        if files and random.random() # Randomly choose to add a file or directory
            file_or_dir = random.choice(files + dirs)
            current_size += file_or_dir.stat().st_size
            combination.append(file_or_dir)
            if
isinstance
(file_or_dir, Path) and file_or_dir.is_file():
                files.remove(file_or_dir)  # Remove the selected file to avoid duplicates
            elif
isinstance
(file_or_dir, Path) and file_or_dir.is_dir():
                dirs.remove(file_or_dir)
        else:
            break

    return combination
def split_directory(dir_path: Path, target_dir_name:
str
, min_size:
int
, max_size:
int
):
    base_dir = Path(dir_path.parent, target_dir_name)
    # If the original directory size is greater than or equal to 3GB, create multiple subdirectories and randomly distribute files
    if get_dir_size(dir_path) >= min_size *
[color=]1024
**
[color=]3
:
        i = 1
[color=]        
total_size = get_dir_size(dir_path)
        while total_size >= min_size *
[color=]1024
**
[color=]3
:
            sub_dir = base_dir / f"{target_dir_name}{i}"
            sub_dir.mkdir(
exist_ok
=True)
            # Get a random combination and move it to the new subdirectory
            combination = random_combination(dir_path, min_size *
[color=]1024
**
[color=]3
, max_size *
[color=]1024
**
[color=]3
)
            for item in combination:
                if item.is_file() and not item.parent == dir_path:  # Skip files that are already in subdirectories
                    continue

                dest_item = sub_dir / item.name
                if dest_item.exists():  # Skip the item if it already exists in the destination
                    
print
(f"Skipping {item} because it already exists in {sub_dir}")
                    continue
                shutil.move(
str
(item),
str
(sub_dir))
            # Update the total remaining size after moving items
            total_size -=
sum
([entry.stat().st_size for entry in combination if entry.is_file()])
            i += 1
if __name__ == "__main__":
    source_dir = Path("G:/shangchang")
    target_dir_name = "shangchang"
    min_size_gb = 3
[color=]   
max_size_gb = 4.9
[color=]   
split_directory(source_dir, target_dir_name, min_size_gb, max_size_gb)经测试上面的代码不符合要求。

文件, 随机

1e3e
OP
  

我自己来回答吧,下面这段代码可行:
import os
import shutil
import zipfile
import random
# 清空 G:\\output 目录
shutil.rmtree("G:\\output", ignore_errors=True)
os.makedirs("G:\\output")
# Get the current working directory
cwd = os.getcwd()
# Change the working directory to the `G:\shangchang` folder
os.chdir('G:/shangchang')
# Iterate over the first-level subdirectories in the `G:\shangchang` folder
for subdir in os.listdir():
    if os.path.isdir(subdir):
        # Create a ZIP archive of the subdirectory
        with zipfile.ZipFile(f'{subdir}.zip', 'w') as zip_file:
            for root, dirs, files in os.walk(subdir):
                for file in files:
                    zip_file.write(os.path.join(root, file))
        # Delete the subdirectory
        shutil.rmtree(subdir)
# Change the working directory back to the original directory
os.chdir(cwd)
# 第二部分代码实际上也可单独运行Get the current working directory
cwd = os.getcwd()
# Change the working directory to the `G:\shangchang` folder
os.chdir('G:/shangchang')
# Get a list of all the files in the `G:\shangchang` folder
files = [f for f in os.listdir() if os.path.isfile(f)]
# Create a new folder named `output` in the G drive
os.makedirs('G:/output', exist_ok=True)
# Iterate over the files in the `G:\shangchang` folder
while files:
    # Get a random combination of files
    combination = random.sample(files, random.randint(1, len(files)))
    # Calculate the total size of the combination
    total_size = sum(os.path.getsize(f) for f in combination)
    # If the total size of the combination is greater than 3GB but less than 4GB
    if 3 * 1024**3 [Python] 纯文本查看 复制代码import os
import shutil
import random
from pathlib import Path
def get_dir_size(dir_path: Path) -> int:
    total = 0
    for entry in dir_path.iterdir():
        if entry.is_file():
            total += entry.stat().st_size
        elif entry.is_dir():
            total += get_dir_size(entry)
    return total
def random_combination(dir_path: Path, min_size: int, max_size: int):
    files = [f for f in dir_path.iterdir() if f.is_file()]
    dirs = [d for d in dir_path.iterdir() if d.is_dir()]
    # Randomly choose files and/or directories until the combination size meets the criteria
    current_size = 0
    combination = []
    while current_size  max_size):
        if files and random.random() = min_size * 1024**3:
            sub_dir = dir_path.parent / f"{target_dir_name}{i}"
            sub_dir.mkdir(exist_ok=True)
            # Get a random combination and move it to the new subdirectory
            combination = random_combination(dir_path, min_size * 1024**3, max_size * 1024**3)
            for item in combination:
                if item.is_file() and not item.parent == dir_path:  # Skip files that are already in subdirectories
                    continue
                dest_item = sub_dir / item.name
                if dest_item.exists():  # Skip the item if it already exists in the destination
                    print(f"Skipping {item} because it already exists in {sub_dir}")
                    continue
                shutil.move(str(item), str(sub_dir))
            # Update the total remaining size after moving items
            total_size -= sum([entry.stat().st_size for entry in combination if entry.is_file()])
            i += 1
if __name__ == "__main__":
    source_dir = Path("G:/shangchang")
    target_dir_name = "shangchang"
    min_size_gb = 3
    max_size_gb = 4.9
    split_directory(source_dir, target_dir_name, min_size_gb, max_size_gb)
Focalors   

需要把G:\shangchang目录下的所有文件进行组合放置到G:\shangchang1...里
最终每个文件夹大小在3-4.9G之间(估计会存在一个不到3G的也单独放就行)
转换下思路 是不是可以获取文件夹下的所有文件,然后随机取几个组合,符合3-4.9的就建个文件夹丢进去,不够的就在随机组进来一个,超过的话再换一个,最后可能剩下一个不到3的再放进一个文件夹 (ps:前提每个文件都不超过4.9G)
lorzl   


lorzl 发表于 2024-4-15 17:02
需要把G:\shangchang目录下的所有文件进行组合放置到G:\shangchang1...里
最终每个文件夹大小在3-4.9G之间 ...

不是的,我不想破坏原来的一级子目录,我是将一级子目录视同为一个文件处理,这样实际就是该文件夹中随机文件进行组合,只要大小超过3gb且小于4.9gb就新建个文件夹丢进去。
1e3e
OP
  


Focalors 发表于 2024-4-15 17:00
搞不懂,AI写的,感觉跟原来的代码一样?
[mw_shl_code=python,true]import os
import shutil

代码什么都没发生过,不是我要的
您需要登录后才可以回帖 登录 | 立即注册

返回顶部