Linux | 大文件上传/下载麻烦、容易中断,如何分割上传/下载

4499937a56bad1777e5982a095dd89b7.png

不知道你有没有遇到过类似情况:一个几百G的文件要上传到百度云或者其他地方,本地网络不稳定的时候经常断,断了就得重新输入指令或者选择上传。

文本段落分享如何将本地大文件分割,这样我们可以同时上传多个分割后的文件。

Mac 和 Linux 下都可以直接使用split指令:

# 把 temp.txt 分割成5块
split  -n 5  temp.txt temp-part-

合并方法:

cat temp-part-* > combined_temp.txt

Windows 下比价复杂,建议直接使用Python代码实现,脚本如下:

import os

def split_file(file_path, output_dir, num_chunks):
    '''
    file_path: 要分割的文件
    output_dir: 分割后文件存放目录
    num_chunks: 分割块数
    '''
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    file_size = os.path.getsize(file_path)
    chunk_size = file_size // num_chunks
    with open(file_path, 'rb') as f:
        for i in range(num_chunks):
            chunk_file = os.path.join(output_dir, f'chunk_{i}.part')
            with open(chunk_file, 'wb') as chunk:
                chunk.write(f.read(chunk_size))
        # Write any remaining bytes (for non-even division of file size)
        remaining_data = f.read()
        if remaining_data:
            with open(os.path.join(output_dir, f'chunk_{num_chunks}.part'), 'wb') as chunk:
                chunk.write(remaining_data)

# 使用示例
split_file('largefile.txt', 'output_chunks', 5)

合并代码:

def merge_files(input_dir, output_file):
    '''
    input_dir: 要合并文件所在文件夹
    output_file: 合并后文件路径
    '''
    with open(output_file, 'wb') as f:
        for chunk_file in sorted(os.listdir(input_dir)):
            with open(os.path.join(input_dir, chunk_file), 'rb') as chunk:
                f.write(chunk.read())

# 使用示例
merge_files('output_chunks', 'combined_largefile.txt')

以上,over

如有其他问题,欢迎评论!我是老表,我的微信:pythonbrief

关注我,学习跟多实用技巧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

简说Python

多多少少都是爱,感谢充电。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值