python实现按行切分文本文件的方法

yipeiwu_com6年前Python基础

本文实例讲述了python实现按行切分文本文件的方法。分享给大家供大家参考,具体如下:

python脚本利用shell命令来实现文本的操作, 这些命令大大减少了我们的代码量。

比如按行切分文件并返回切分后得到的文件列表,可以利用内建的split命令进行切分。为了返回得到的文件列表名,可以先将文件切分到自建的子目录中,然后通过os.listdir获取所有文件,再将这些文件移到上一级目录(即函数参数指定的新目录),删除自建子目录,最后返回该文件名列表。

代码如下,如发现问题欢迎指正:

# 创建新路径
def make_dirs(path):
  if not os.path.isdir(path):
    os.makedirs(path)
# 获取文件的行数
def get_total_lines(file_path):
  if not os.path.exists(file_path):
    return 0
  cmd = 'wc -l %s' % file_path
  return int(os.popen(cmd).read().split()[0])
# 函数split_file_by_row: 按行切分文件
# filepath: 切分的目标文件
# new_filepath: 生成新文件的路径
# row_cnt: 每个文件最多包含几行
# suffix_type: 新文件后缀类型,如两位字母或数字
# return: 切分后的文件列表
def split_file_by_row(filepath, new_filepath, row_cnt, suffix_type='-d'):
  tmp_dir = "/split_file_by_row/"
  make_dirs(new_filepath)
  make_dirs(new_filepath+tmp_dir)
  total_rows = get_total_lines(filepath)
  file_cnt = int(math.ceil(total_rows*1.0/row_cnt))
    command = "split -l%d -a2 %s %s %s" % (row_cnt, suffix_type, filepath, new_filepath+tmp_dir)
    os.system(command)
    filelist = os.listdir(new_filepath+tmp_dir)
  command = "mv %s/* %s"%(new_filepath+tmp_dir, new_filepath)
  os.system(command)
  command = "rm -r %s"%(new_filepath+tmp_dir)
  os.system(command)
  return [new_filepath+fn for fn in filelist]

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

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

相关文章

初次部署django+gunicorn+nginx的方法步骤

环境 ubuntu16.04 python3.6 django1.11 gunicorn19.7.1 nginx1.10.3 写在前面 其实无论是在部署,还是在其他方面,我们总会遇到一...

python中sleep函数用法实例分析

本文实例讲述了python中sleep函数用法。分享给大家供大家参考。具体如下: Python中的sleep用来暂停线程执行,单位为秒 #----------------------...

详解使用Python下载文件的几种方法

在使用Python进行数据抓取的时候,有时候需要保持文件或图片等,在Python中可以有多种方式实现。今天就一起来学习下。 urllib.request 主要使用的是urlretrie...

python+mysql实现学生信息查询系统

python+mysql实现学生信息查询系统

本文实例为大家分享了python mysql学生信息查询系统的具体代码,供大家参考,具体内容如下 import pymysql #import redis #pool = redis...

Python实现的多线程端口扫描工具分享

Python实现的多线程端口扫描工具分享

昨晚今晚写了两晚,总算把Py Port Scanner 写完了,姑且称之为0.1版本,算是一个Python多线程端口扫描工具。 水平有限,实话中间有一些困惑和不解的地方,代码可能也写的比...