python删除文本行_从python中的大文本文件中删除特定行

针对大型文本文件,需要删除前3行并修改第4行特定格式的问题,作者提出了一个Python解决方案。在第4行中,将“Rx(db)”更改为“Rx”,并将“Best Unit”替换为“Best_Unit”。由于前3行的数值不同,不能直接使用grep等命令行工具,而是采用读取并处理文件内容的方式。然而,提供的代码在处理大文件时出现了错误。
摘要由CSDN通过智能技术生成

我有几个大的文本文本文件都具有相同的结构,我想删除前3行,然后从第4行删除非法字符.我不想读取整个数据集然后修改,因为每个文件超过100MB,超过400万条记录.

Range 150.0dB -64.9dBm

Mobile unit 1 Base -17.19968 145.40369 999.8

Fixed unit 2 Mobile -17.20180 145.29514 533.0

Latitude Longitude Rx(dB) Best unit

-17.06694 145.23158 -050.5 2

-17.06695 145.23297 -044.1 2

因此应该删除第1,2和3行,在第4行中,“Rx(db)”应该只是“Rx”而“Best Unit”应该更改为“Best_Unit”.然后我可以使用我的其他脚本对数据进行地理编码.

我不能使用像grep(as in this question)这样的命令行程序,因为前3行并不完全相同 – 每个文件中的数字(例如150.0dB,-64 *)都会改变,所以你必须删除整行1-3然后grep或类似的可以在第4行进行搜索替换.

多谢你们,

===编辑新的pythonic方法来处理来自@heltonbiker的更大文件.错误.

import os, re

##infile = arcpy.GetParameter(0)

##chunk_size = arcpy.GetParameter(1) # number of records in each dataset

infile='trc_emerald.txt'

fc= open(infile)

Name = infile[:infile.rfind('.')]

outfile = Name+'_db.txt'

line4 = fc.readlines(100)[3]

line4 = re.sub('\([^\)].*?\)', '', line4)

line4 = re.sub('Best(\s.*?)', 'Best_', line4)

newfilestring = ''.join(line4 + [line for line in fc.readlines[4:]])

fc.close()

newfile = open(outfile, 'w')

newfile.write(newfilestring)

newfile.close()

del lines

del outfile

del Name

#return chunk_size, fl

#arcpy.SetParameterAsText(2, fl)

print "Completed"

Traceback (most recent call last): File “P:\2012\Job_044_DM_Radio_Propogation\Working\FinalPropogation\TRC_Emerald\working\clean_file_1c.py”,

line 13, in

newfilestring = ”.join(line4 + [line for line in fc.readlines[4:]]) TypeError: ‘builtin_function_or_method’ object is

unsubscriptable

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值