python 读取txt文件特定字符串后面的数字,并写入到另一个txt

原1.txt文件内容如下:
第一行到第x行:中文内容
第x+1行:2013-06-09 ::去的时间: 300/n耽误时间: 40回来时间: 200
第x+2行到第y行:中文内容
第y+1行:2013-06-09 ::去的时间: 400/n耽误时间: 50回来时间: 500
如此重复。

结果2.txt:
去的时间 耽误时间 回来时间
300 40 200
400 50 500

分为两个步骤

    使用open函数打开文件,返回文件句柄

    使用文件句柄的read()方法读取文件内容

f = open('/path/to/the/file.txt')
txt = f.read()

txt文件的内容将会读取待txt变量中

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-06-17
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re

def main(input_file, output_file):
    pattern = re.compile('^([0-9]{4}-[0-9]{2}-[0-9]{2}) ::去的时间: ([0-9]+)/n耽误时间: ([0-9]+)回来时间: ([0-9]+)$')
    reader = open(input_file, 'r')
    buff = []
    while True:
        line = reader.readline()
        if len(line) == 0:
            break
        line = line.rstrip()
        m = pattern.match(line)
        if m:
            buff.append("%s %s %s" % (m.group(2), m.group(3), m.group(4)))
    reader.close()
    writer = open(output_file, 'w')
    writer.write('\n'.join(buff))
    writer.close()

if __name__ == '__main__':
    main('zhidao_559728513.input', 'zhidao_559728513.output')

本回答被提问者和网友采纳
第2个回答  2013-06-17
可以搜"python编程思路"视频看看。有一个完整的文本转换的例子
相似回答