Python 逐行分割大txt文件的方法

yipeiwu_com5年前Python基础

代码如下所示:

# -*- coding: <encoding name> -*-
import io
LIMIT = 150000
file_count = 0
url_list = []
with io.open('D:\DB_NEW_bak\DB_NEW_20171009_bak.sql','r',encoding='utf-16') as f:
  for line in f:
    url_list.append(line)
    if len(url_list) < LIMIT:
      continue
    file_name = str(file_count)+".sql"
    with io.open(file_name,'w',encoding='utf-16') as file:
      for url in url_list[:-1]:
        file.write(url)
      file.write(url_list[-1].strip())
      url_list=[]
      file_count+=1
if url_list:
  file_name = str(file_count) + ".sql"
  with io.open(file_name,'w',encoding='utf-16') as file:
    for url in url_list:
      file.write(url)
print('done')

Python从txt文件中逐行读取数据

非常的简单,提供三种方法:

方法一:

f = open("foo.txt")       # 返回一个文件对象 
line = f.readline()       # 调用文件的 readline()方法 
while line: 
  print line,         # 后面跟 ',' 将忽略换行符 
  # print(line, end = '')   # 在 Python 3中使用 
  line = f.readline() 
 
f.close() 

方法二:

for line in open("foo.txt"): 
  print line, 

方法三:

f = open("c:\\1.txt","r") 
lines = f.readlines()#读取全部内容 
for line in lines 
  print line 

总结

以上所述是小编给大家介绍的Python 逐行分割大txt文件,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

Linux(Redhat)安装python3.6虚拟环境(推荐)

python是3.6 centos 6 64位 1.安装python 2.安装pip wget https://bootstrap.pypa.io/get-pip.py --no-c...

对Python Pexpect 模块的使用说明详解

背景介绍 Expect 程序主要用于人机对话的模拟,就是那种系统提问,人来回答 yes/no ,或者账号登录输入用户名和密码等等的情况。因为这种情况特别多而且繁琐,所以很多语言都有各种自...

python循环嵌套的多种使用方法解析

这篇文章主要介绍了python循环嵌套的多种使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用循环嵌套来获取100以内的...

在Linux下使用Python的matplotlib绘制数据图的教程

在Linux下使用Python的matplotlib绘制数据图的教程

如果你想要在Linxu中获得一个高效、自动化、高质量的科学画图的解决方案,应该考虑尝试下matplotlib库。Matplotlib是基于python的开源科学测绘包,基于python软...

Python 中@property的用法详解

在绑定属性时,如果我们直接把属性赋值给对象,比如: p = Person() p.name= 'Mary' 我们先看个详细的例子(注意双下划线name和age定义为私有变量):...