Python text file processing

来源:互联网 发布:qq for mac历史版本 编辑:程序博客网 时间:2024/05/21 14:01

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.


0 0