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

2023-12-15 09:21:36
推荐回答(3个)
回答1:

分为两个步骤

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

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

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

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

回答2:

#!/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')

回答3:

可以搜"python编程思路"视频看看。有一个完整的文本转换的例子