首页 后端开发 Python教程 python分割文件的常用方法

python分割文件的常用方法

Jun 10, 2016 pm 03:19 PM
python 分配 文件

本文大家整理了一些比较好用的关于python分割文件的方法,方法非常的简单实用。分享给大家供大家参考。具体如下:

例子1 指定分割文件大小

配置文件 config.ini:

复制代码 代码如下:
[global]
#原文件存放目录
dir1=F:\work\python\3595\pyserver\test
#新文件存放目录
dir2=F:\work\python\3595\pyserver\test1

python 代码如下:

复制代码 代码如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os,sys,ConfigParser
class file_openate(object):
def __init__(self):
    #初如化读取数据库配置
    dir_config = ConfigParser.ConfigParser()
    file_config=open('config.ini',"rb")
    dir_config.readfp(file_config)
    self.dir1=str(dir_config.get("global","dir1"))
    self.dir1=unicode(self.dir1,'utf8')
    self.dir2=str(dir_config.get("global","dir2"))
    self.dir2=unicode(self.dir2,'utf8')
    file_config.close()
#print self.dir2
#self.dir1="F:\\work\\python\\3595\\pyserver\\test"
def file_list(self):
    input_name_han="软件有不确认性,前期使用最好先备份,以免发生数据丢失,确认备份后,请输入要分割的字节大小,按b来计算".decode('utf-8')
    print input_name_han
    while 1:
input_name=raw_input("number:")
if input_name.isdigit():
    input_name=int(input_name)
    os.chdir(self.dir1)
    for filename in os.listdir(self.dir1):
os.chdir(self.dir1)
#print filename
name, ext = os.path.splitext(filename)
file_size=int(os.path.getsize(filename))
f=open(filename,'r')
chu_nmuber=0
while file_size >= 1:
    #print file_size
    chu_nmuber=chu_nmuber + 1
    if file_size >= input_name:
file_size=file_size - input_name
a=f.read(input_name)
os.chdir(self.dir2)
filename1=name + '-' + str(chu_nmuber) + ext
new_f=open(filename1,'a')
new_f.write(a)
new_f.close()
#print file_size
    else:
a=f.read()
os.chdir(self.dir2)
filename1=name + '-' + str(chu_nmuber) + ext
new_f=open(filename1,'a')
new_f.write(a)
new_f.close()
break
print "分割成功".decode('utf-8') + filename
f.close()
else:
    print "请输入正确的数字,请重新输入".decode('utf-8')
file_name=file_openate()
file_name.file_list()

例子2,按行分割文件大小

复制代码 代码如下:
#!/usr/bin/env python
#--*-- coding:utf-8 --*--
import os
class SplitFiles():
    """按行分割文件"""
    def __init__(self, file_name, line_count=200):
        """初始化要分割的源文件名和分割后的文件行数"""
        self.file_name = file_name
        self.line_count = line_count
    def split_file(self):
        if self.file_name and os.path.exists(self.file_name):
            try:
                with open(self.file_name) as f : # 使用with读文件
                    temp_count = 0
                    temp_content = []
                    part_num = 1
                    for line in f:
                        if temp_count                             temp_count += 1
                        else :
                            self.write_file(part_num, temp_content)
                            part_num += 1
                            temp_count = 1
                            temp_content = []
                        temp_content.append(line)
                    else : # 正常结束循环后将剩余的内容写入新文件中
                        self.write_file(part_num, temp_content)
            except IOError as err:
                print(err)
        else:
            print("%s is not a validate file" % self.file_name)
    def get_part_file_name(self, part_num):
        """"获取分割后的文件名称:在源文件相同目录下建立临时文件夹temp_part_file,然后将分割后的文件放到该路径下"""
        temp_path = os.path.dirname(self.file_name) # 获取文件的路径(不含文件名)
        part_file_name = temp_path + "temp_part_file"
        if not os.path.exists(temp_path) : # 如果临时目录不存在则创建
            os.makedirs(temp_path)
        part_file_name += os.sep + "temp_file_" + str(part_num) + ".part"
        return part_file_name
    def write_file(self, part_num, *line_content):
        """将按行分割后的内容写入相应的分割文件中"""
        part_file_name = self.get_part_file_name(part_num)
        print(line_content)
        try :
            with open(part_file_name, "w") as part_file:
                part_file.writelines(line_content[0])
        except IOError as err:
            print(err)
if __name__ == "__main__":
    sf = SplitFiles(r"F:\multiple_thread_read_file.txt")
    sf.split_file()

上面只是进行了分割了,如果我们又要合并怎么办呢?下面这个例子可以实现分割与合并哦,大家一起看看。

例子3, 分割文件与合并函数

复制代码 代码如下:
#!/usr/bin/python
##########################################################################
# split a file into a set of parts; join.py puts them back together;
# this is a customizable version of the standard unix split command-line
# utility; because it is written in Python, it also works on Windows and
# can be easily modified; because it exports a function, its logic can
# also be imported and reused in other applications;
##########################################################################
     
import sys, os
kilobytes = 1024
megabytes = kilobytes * 1000
chunksize = int(1.4 * megabytes)   # default: roughly a floppy
     
def split(fromfile, todir, chunksize=chunksize):
    if not os.path.exists(todir):  # caller handles errors
os.mkdir(todir)    # make dir, read/write parts
    else:
for fname in os.listdir(todir):    # delete any existing files
    os.remove(os.path.join(todir, fname))
    partnum = 0
    input = open(fromfile, 'rb')   # use binary mode on Windows
    while 1:       # eof=empty string from read
chunk = input.read(chunksize)      # get next part if not chunk: break
partnum  = partnum+1
filename = os.path.join(todir, ('part%04d' % partnum))
fileobj  = open(filename, 'wb')
fileobj.write(chunk)
fileobj.close()    # or simply open().write()
    input.close()
    assert partnum     return partnum
    
if __name__ == '__main__':
    if len(sys.argv) == 2 and sys.argv[1] == '-help':
print 'Use: split.py [file-to-split target-dir [chunksize]]'
    else:
if len(sys.argv)     interactive = 1
    fromfile = raw_input('File to be split? ')       # input if clicked
    todir    = raw_input('Directory to store part files? ')
else:
    interactive = 0
    fromfile, todir = sys.argv[1:3]  # args in cmdline
    if len(sys.argv) == 4: chunksize = int(sys.argv[3])
absfrom, absto = map(os.path.abspath, [fromfile, todir])
print 'Splitting', absfrom, 'to', absto, 'by', chunksize
     
try:
    parts = split(fromfile, todir, chunksize)
except:
    print 'Error during split:'
    print sys.exc_info()[0], sys.exc_info()[1]
else:
    print 'Split finished:', parts, 'parts are in', absto
if interactive: raw_input('Press Enter key') # pause if clicked

join_file.py
 

复制代码 代码如下:
#!/usr/bin/python
##########################################################################
# join all part files in a dir created by split.py, to recreate file. 
# This is roughly like a 'cat fromdir/* > tofile' command on unix, but is
# more portable and configurable, and exports the join operation as a
# reusable function.  Relies on sort order of file names: must be same
# length.  Could extend split/join to popup Tkinter file selectors.
##########################################################################
     
import os, sys
readsize = 1024
     
def join(fromdir, tofile):
    output = open(tofile, 'wb')
    parts  = os.listdir(fromdir)
    parts.sort()
    for filename in parts:
filepath = os.path.join(fromdir, filename)
fileobj  = open(filepath, 'rb')
while 1:
    filebytes = fileobj.read(readsize)
    if not filebytes: break
    output.write(filebytes)
fileobj.close()
    output.close()
     
if __name__ == '__main__':
    if len(sys.argv) == 2 and sys.argv[1] == '-help':
print 'Use: join.py [from-dir-name to-file-name]'
    else:
if len(sys.argv) != 3:
    interactive = 1
    fromdir = raw_input('Directory containing part files? ')
    tofile  = raw_input('Name of file to be recreated? ')
else:
    interactive = 0
    fromdir, tofile = sys.argv[1:]
absfrom, absto = map(os.path.abspath, [fromdir, tofile])
print 'Joining', absfrom, 'to make', absto
     
try:
    join(fromdir, tofile)
except:
    print 'Error joining files:'
    print sys.exc_info()[0], sys.exc_info()[1]
else:
   print 'Join complete: see', absto
if interactive: raw_input('Press Enter key') # pause if clicked

希望本文所述对大家的Python程序设计有所帮助。

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

PHP和Python:解释了不同的范例 PHP和Python:解释了不同的范例 Apr 18, 2025 am 12:26 AM

PHP主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。

Python vs. JavaScript:学习曲线和易用性 Python vs. JavaScript:学习曲线和易用性 Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

在PHP和Python之间进行选择:指南 在PHP和Python之间进行选择:指南 Apr 18, 2025 am 12:24 AM

PHP适合网页开发和快速原型开发,Python适用于数据科学和机器学习。1.PHP用于动态网页开发,语法简单,适合快速开发。2.Python语法简洁,适用于多领域,库生态系统强大。

vs code 可以在 Windows 8 中运行吗 vs code 可以在 Windows 8 中运行吗 Apr 15, 2025 pm 07:24 PM

VS Code可以在Windows 8上运行,但体验可能不佳。首先确保系统已更新到最新补丁,然后下载与系统架构匹配的VS Code安装包,按照提示安装。安装后,注意某些扩展程序可能与Windows 8不兼容,需要寻找替代扩展或在虚拟机中使用更新的Windows系统。安装必要的扩展,检查是否正常工作。尽管VS Code在Windows 8上可行,但建议升级到更新的Windows系统以获得更好的开发体验和安全保障。

visual studio code 可以用于 python 吗 visual studio code 可以用于 python 吗 Apr 15, 2025 pm 08:18 PM

VS Code 可用于编写 Python,并提供许多功能,使其成为开发 Python 应用程序的理想工具。它允许用户:安装 Python 扩展,以获得代码补全、语法高亮和调试等功能。使用调试器逐步跟踪代码,查找和修复错误。集成 Git,进行版本控制。使用代码格式化工具,保持代码一致性。使用 Linting 工具,提前发现潜在问题。

PHP和Python:深入了解他们的历史 PHP和Python:深入了解他们的历史 Apr 18, 2025 am 12:25 AM

PHP起源于1994年,由RasmusLerdorf开发,最初用于跟踪网站访问者,逐渐演变为服务器端脚本语言,广泛应用于网页开发。Python由GuidovanRossum于1980年代末开发,1991年首次发布,强调代码可读性和简洁性,适用于科学计算、数据分析等领域。

vscode怎么在终端运行程序 vscode怎么在终端运行程序 Apr 15, 2025 pm 06:42 PM

在 VS Code 中,可以通过以下步骤在终端运行程序:准备代码和打开集成终端确保代码目录与终端工作目录一致根据编程语言选择运行命令(如 Python 的 python your_file_name.py)检查是否成功运行并解决错误利用调试器提升调试效率

vscode 扩展是否是恶意的 vscode 扩展是否是恶意的 Apr 15, 2025 pm 07:57 PM

VS Code 扩展存在恶意风险,例如隐藏恶意代码、利用漏洞、伪装成合法扩展。识别恶意扩展的方法包括:检查发布者、阅读评论、检查代码、谨慎安装。安全措施还包括:安全意识、良好习惯、定期更新和杀毒软件。

See all articles