python读取配置文件 分段_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,ConfigParserclass 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 filenamename, ext =
os.path.splitext(filename)file_size=int(os.path.getsize(filename))f=open(filename,'r')chu_nmuber=0while
file_size >= 1: #print file_size chu_nmuber=chu_nmuber +
1 if file_size >= input_name:file_size=file_size -
input_namea=f.read(input_name)os.chdir(self.dir2)filename1=name +
'-' + str(chu_nmuber) +
extnew_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) +
extnew_f=open(filename1,'a')new_f.write(a)new_f.close()breakprint
"分割成功".decode('utf-8') + filenamef.close()else: print
"请输入正确的数字,请重新输入".decode('utf-8')file_name=file_openate()file_name.file_list()
例子2,按行分割文件大小
复制代码
代码如下:
#!/usr/bin/env python#--*-- coding:utf-8
--*--import osclass 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 <
self.line_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, oskilobytes = 1024megabytes = kilobytes *
1000chunksize = int(1.4 * megabytes) # default: roughly a floppy
def split(fromfile, todir, chunksize=chunksize): if not
os.path.exists(todir): # caller handles errorsos.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 readchunk =
input.read(chunksize) # get next part <= chunksizeif not chunk:
breakpartnum = partnum+1filename = os.path.join(todir, ('part%04d' %
partnum))fileobj = open(filename,
'wb')fileobj.write(chunk)fileobj.close() # or simply
open().write() input.close() assert partnum <= 9999 # join sort
fails if 5 digits 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) < 3: 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', abstoif 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, sysreadsize = 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', abstoif interactive: raw_input('Press Enter key') # pause if
clicked
小编推荐:欲学习电脑技术、系统维护、网络管理、编程开发和安全攻防等高端IT技术,请 点击这里注册账号,公开课频道价值万元IT培训教程免费学,让您少走弯路、事半功倍,好工作升职加薪!
免责声明:本站系公益性非盈利IT技术普及网,本文由投稿者转载自互联网的公开文章,文末均已注明出处,其内容和图片版权归原网站或作者所有,文中所述不代表本站观点,若有无意侵权或转载不当之处请从网站右下角联系我们处理,谢谢合作!
python读取配置文件 分段_python分割文件的常用方法相关推荐
- python读取配置文件 分段_python配置文件读取
(这家伙很懒,直接复制官方文档尴尬) 使用方法如下: importconfigparser config=configparser.ConfigParser() config.read(configF ...
- python读取配置文件 分段_Python3读写ini配置文件的示例
ini文件即Initialization File初始化文件,在应用程序及框架中常作为配置文件使用,是一种静态纯文本文件,使用记事本即可编辑. 配置文件的主要功能就是存储一批变量和变量值,在ini文件 ...
- python读取一行数组_python 把文件中的每一行以数组的元素放入数组中的方法
有时候需要把文件中的数据放入到数组中,这里提供了一种方法,可以根据文件结尾的标记进行数据拆分,然后再把拆分的文件放入数组中 # -*-coding: utf-8 -*- f = open(" ...
- python读取坐标文本文件_Python 实现文件读写、坐标寻址、查找替换功能
读文件 打开文件(文件需要存在) #打开文件 f = open("data.txt","r") #设置文件对象 print(f)#文件句柄 f.close() ...
- python读取配置文件使用_python 使用 ConfigParser 读取和修改INI配置文件
在程序开发中,使用独立的配置文件来配置一些参数常见且方便,配置文件的解析或修改并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,ConfigP ...
- python读取配置文件存在某配置_Python读取配置文件(config.ini)以及写入配置文件
一.读取配置文件 我的目录如下,在config下有一个config.ini配置文件 配置文件内容# 定义config分组 [config] platformName=Android appPackag ...
- python火狐配置文件_Python+Selenium中级篇之4-封装一个自己的类-浏览器引擎类/Python读取配置文件内容...
封装一个自己的类-浏览器引擎类 前一篇文章我们知道了,如何去封装几个简单的Selenium方法到我们自定义的类,这次我们编写一个类,叫浏览器引擎类,通过更改一个字符串的值,利用if语句去判断和控制启动 ...
- python读取配置文件获取所有键值对_python读取配置文件 变量 ConfigParser模块
Python 读取写入配置文件很方便,可使用内置的 configparser 模块 配置文件:config.ini [oppo] platformName = Android platformVers ...
- python读取配置文件失败原因_python读取配置文件报keyerror-文件路径不正确导致的错误...
- 在其他模块使用反射读取配置文件报错,但是在反射模块中读取GetData.check_list又是正确的 反射模块如下: # get_data.py from API_AUTO.p2p_projec ...
最新文章
- tomcat_deploy 平滑启动脚本
- vs2010 使用vs online账号 需要安装的插件
- 来自于参赛队伍所反映的总决赛落选之后的建议
- vue 中eslint 格式报错
- 使用 VMware + win10 + vs2019 从零搭建双机内核调试环境
- java发送c语言结构体_C语言中结构体直接赋值?
- isfull mysql_MySQL数据库之MySQL 出现 The table is full 的解决方法
- 工作室流量卡如何做才能不封号?
- ubuntu中非常好用的PDF软件—okular
- php 获取搜索引擎,php获取搜索引擎关键字来源(支持百度、谷歌等搜索引擎)的函数...
- 计算机的发明是现代科学的奇迹之一翻译,04统考阅读新题型50篇翻译.pdf
- 使用Servlet和JSP开发Java应用程序 ----错误处理
- 数据库优化及淘宝主键设计
- 数据结构的C实现_二叉树
- Sql 存储过程传递参数
- html-webpack-plugin 又出幺蛾子 | 一次解决bug的过程
- Flutter 实现原理及跨平台实践
- 【计算机网络】定义、作用、特点计算机网络
- 拼车小程序的盈利模式探究,以及快速有效的推广方法!【小程序创业干货】
- STL优先队列实现堆(模板 附力扣题目)
热门文章
- 7个等级 容灾等级_容灾备份的柒个国际标准等级(一)
- 星星之火-36:LTE载波载波的间隔是15K, 载波波的带宽是多少? 15K还是30K?
- 【PyTorch训练中Dataset多线程加载数据,比Dataloader里设置多个workers还要快】
- TDengine总结物联网数据特点
- 图片+css实现波浪
- 应用在生物医学领域中的NLP预训练语言模型(PubMedBERT)
- base64编码图片数据存储服务器
- pat 乙级 1094
- 【Android】RecycleView简单仿漫画APP图片相关样式
- csgo如何保存自己的cfg_[CS:GO]如何导出cfg文件 最新方法[已解决]