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.
本文分享了使用Python进行文本文件处理的实用技巧,包括文件的打开与关闭、逐行读取、特殊字符分割等操作,通过示例代码演示如何轻松处理大量文件。
1062

被折叠的 条评论
为什么被折叠?



