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

Python实现移除文件中-port:后随机整数时代码报错如何解决?

解决移除文件中-port:后整数的问题

问题说明

需要打开blah.txt文件,移除标识“-port:”后小于100的整数(目标文件内容为“-port:4”),但运行代码时出现如下错误:

"File "p:\Python______________\Automating scripts\demo.py", line 25, in
f.write(content.replace('-port:'+range, '-port:'))"

原代码如下:

range = [1 - 100]
with open ('P:\\blah.txt', 'r+') as f:
    content = f.read()
    f.seek(0)
    f.write(content.replace('-port:'+range, '-port:'))
    print('\nScript ready')       

错误原因

  1. 变量定义错误:[1 - 100]会计算为[-99],是一个列表,无法直接和字符串'-port:'拼接,这是报错的直接原因。
  2. 思路错误:试图用固定值匹配替换,但需要处理所有1-99的整数,枚举方式不现实,应该用正则表达式匹配数字。

修正方案

使用正则表达式匹配“-port:”后的1-2位数字(对应小于100的整数),替换为“-port:”,同时处理文件截断问题避免残留内容。

完整代码

import re

with open('P:\\blah.txt', 'r+') as f:
    content = f.read()
    # 匹配-port:后1到2位数字,替换为-port:
    updated_content = re.sub(r'-port:\d{1,2}', '-port:', content)
    f.seek(0)
    f.write(updated_content)
    f.truncate()  # 截断文件,清除原内容中多余部分
print('\nScript ready')

代码说明

  • re.sub(pattern, repl, string):正则替换函数,r'-port:\d{1,2}'匹配“-port:”后跟1-2位数字的字符串,替换为'-port:'。
  • f.truncate():因为r+模式下写入新内容后,若新内容长度小于原文件,旧内容末尾会残留,此方法截断文件至当前写入位置,确保文件内容完全更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:35:18