You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python删除特定时间子串行失败:输出文件为空如何解决?

问题排查与解决方法

先确认基础问题

  • 检查脚本和input_file.txt是否在同一目录,若不在,把代码里的文件名换成绝对路径(比如C:/test/input_file.txt或/home/user/input_file.txt)。
  • 手动打开输入文件,确认里面确实存在包含T18、T19或T20的行——别排除文件本身就没有符合条件数据的情况。

处理文件编码问题

有些文本文件用非UTF-8编码(比如GBK、UTF-16),默认open读取会乱码,导致匹配失败。可以:

  1. 指定编码打开文件:
with open('input_file.txt', 'r', encoding='utf-8') as input_file, open('output_file.txt', 'w', encoding='utf-8') as output_file:
    for line in input_file:
        if 'T18' in line or 'T19' in line or 'T20' in line:
            output_file.write(line)
  1. 如果不知道编码,用chardet库检测:
    先安装库:pip install chardet
    再运行检测代码:
import chardet
with open('input_file.txt', 'rb') as f:
    result = chardet.detect(f.read())
print(result['encoding'])

把输出的编码值替换到open的encoding参数里。

优化匹配逻辑(避免格式差异)

  • 如果时间里的T是小写t,改成不区分大小写的匹配:
with open('input_file.txt', 'r', encoding='utf-8') as input_file, open('output_file.txt', 'w', encoding='utf-8') as output_file:
    for line in input_file:
        line_lower = line.lower()
        if 't18' in line_lower or 't19' in line_lower or 't20' in line_lower:
            output_file.write(line)
  • 若要避免其他字段误匹配(比如某个字符串里刚好有T18),可以用CSV解析精准提取时间:
import csv
with open('input_file.txt', 'r', encoding='utf-8') as input_file, open('output_file.txt', 'w', encoding='utf-8', newline='') as output_file:
    reader = csv.reader(input_file)
    writer = csv.writer(output_file)
    for row in reader:
        if not row:
            continue
        time_str = row[0].strip('"')
        hour = time_str.split('T')[1].split(':')[0]
        if hour in {'18', '19', '20'}:
            writer.writerow(row)

内容的提问来源于stack exchange,提问作者Ediz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 07:42:56