【问题标题】:Text file editing and line writing文本文件编辑和行写入
【发布时间】:2018-04-17 20:30:30
【问题描述】:

我的代码有点小问题。

首先是代码:

import os
import subprocess
import httplib, urllib

for ip in range(1,255):

   ip_addr = "192.168.1." + str(ip)
   res = subprocess.call(["ping", ip_addr, "-c1", "-W1", "-q"], stdout=open(os.devnull,'w'))
   if res == 0:
      print (ip_addr) + " reachable"
   else:
      print (ip_addr) + " not reachable"

   f = open('state_All.txt','r')
   prestate = f.readline(ip)
   f.close()
   prestate = ord(prestate)
   res = res + 97
   if not prestate == res:
      if prestate == 97:
         conn = httplib.HTTPSConnection("api.pushover.net:443")
         ## The Code in here which I have deleted out is definitely not the problem,
         ## works 100% safe and can't be share beacuse of security problems.
          }), { "Content-type": "application/x-www-form-urlencoded" })
         conn.getresponse()
      else:
         conn = httplib.HTTPSConnection("api.pushover.net:443")
         ## The Code in here which I have deleted out is definitely not the problem,
         ## works 100% safe and can't be share beacuse of security problems.
          }), { "Content-type": "application/x-www-form-urlencoded" })
         conn.getresponse()
   f = open('state_All.txt','w')
   res = str(unichr(res))
   data = (res[ip])
   f.writelines(data)
   f.close()

问题:

读取 .txt 中的某些特定行有效,但我无法在特定行上写入之后的测量状态,

我收到了这个错误:

Traceback (most recent call last):
  File "ping_All.py", line 48, in <module>
    data = (res[ip])
IndexError: string index out of range

希望有人可以帮助我。

【问题讨论】:

  • 看起来res 的字符串长度不超过 255 个字符...为什么使用ip 作为字符串索引?第 48 行引发错误的操作是尝试访问字符串中的字符,但您的字符串不够长。

标签: python text-files


【解决方案1】:

当您尝试从该字符串访问项目时,您会得到index out of range。这意味着您尝试访问一个项目,在您的情况下是一个字符,其中索引 (ip) 大于 res 的长度或小于 0。

【讨论】:

    猜你喜欢
    • 2011-05-22
    • 2018-10-25
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    相关资源
    最近更新 更多