简体   繁体   English

python中的file.write()

[英]file.write() in python

import os
import sys
import re
import string

f=open('./iprange','r')
s=f.readline()
f.close()
pattern='inet addr:'+s
pattern=pattern.split('x')[0]
pattern='('+pattern+'...'+')'

os.system('ifconfig -a >> interfaces')
f=open('./interfaces','r')
s=f.readline()

while (len(s))!=0:
    i=re.search(pattern,s)
    if i!=None:
        sp=re.split(pattern,s)[1]
        ip=re.split('inet addr:',sp)[1]
        break
    s=f.readline()

f.close()
os.system('rm ./interfaces')
f=open('./userip','w')
f.write(ip)
f.close()

NameError;name 'ip' is not defined

I split pattern by s and store the result in sp , then I find the IP address and store the result in ip . 我用s分割pattern并将结果存储在sp ,然后找到IP地址并将结果存储在ip But the error says ip is not defined - what's going on? 但是错误显示ip未定义-怎么回事?

while (len(s))!=0:
    i=re.search(pattern,s)
    if i!=None:
        sp=re.split(pattern,s)[1]
        ip=re.split('inet addr:',sp)[1]
        break
    s=f.readline()

The ip assignment is inside the if closure, which is apparently never being executed. ip赋值位于if闭包内部,这显然从未执行过。

I'd do something more like this: 我会做更多这样的事情:

import os
import sys
import re
from itertools import takewhile

with open('./iprange','r') as f:
    s = f.readline()

prefix = 'inet addr:'
pattern = prefix + s
pattern = pattern.split('x')[0]
pattern = '(%s...)' % pattern

os.system('ifconfig -a >> interfaces')
with open('interfaces', 'r') as f:
    # Put all lines up to the first empty line into a list
    # http://docs.python.org/2/library/itertools.html#itertools.takewhile
    # `[line.rstrip() for line in f]` could be a generator instead:
    # (line.rstrip() for line in f)
    lines = list(takewhile(lambda x: x, [line.rstrip() for line in f]))
os.remove('interfaces')

for s in lines:
    if re.search(pattern, s):
        sp = re.split(pattern, s)[1]
        ip = sp[len(prefix):]
        with open('./userip', 'w') as f:
            f.write(ip)
        break
else:
    print "No match found"

For one thing, you only write to the file userip if you find a match and you get a message if no match was found. 一方面,仅当找到匹配项时才写入文件userip如果找不到匹配项,则会收到一条消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM