Python text file processing

Have done quite a few text file processing job in work, some tips of using python for text processing,

1, file open and close, in most cases, you will need to process all the files inside one folder, or all the files with the same extension inside one folder, to process the files one by one, this can be done by using following example as,

src = "D:\\mywork\\"
filenamelist=os.listdir(src)
for y in xrange(len(filenamelist)):
    #process your file here.

to open a file,

inputfile = open(src + filenamelist[y], 'r')

to close a file,

inputfile.close()


2,  to process the file one line by one line, you can use the loop logic as,

for eachline in inputfile:

normally you will need to modify something and write to a new file, you just need to open a new file and write to the new file, after process each line, the write back will be as following, the output file will be the file opened for written,

outputfile.write(eachline)

if you need to retrieve each line information split by some special characters for example space ' ', you can use following command as,

colunmA,colunmB,colunmC= str(eachline).split(' ')

In this way, you can process lots of files easily in one Python programming running.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值