我正在尝试将字符串值声明为等于行号的文本。
文件我用作验证表的文件的内容
domain1
=============================
xx-xx-xx-xx-xx-xx pc1
xx-xx-xx-xx-xx-xx pc2
xx-xx-xx-xx-xx-xx pc3
xx-xx-xx-xx-xx-xx pc4
xx-xx-xx-xx-xx-xx pc5
xx-xx-xx-xx-xx-xx pc6
xx-xx-xx-xx-xx-xx pc7
xx-xx-xx-xx-xx-xx pc8
xx-xx-xx-xx-xx-xx pc9
xx-xx-xx-xx-xx-xx pc10
=============================
domain2
=============================
xx-xx-xx-xx-xx-xx pc1
xx-xx-xx-xx-xx-xx pc2
xx-xx-xx-xx-xx-xx pc3
xx-xx-xx-xx-xx-xx pc4
xx-xx-xx-xx-xx-xx pc5
xx-xx-xx-xx-xx-xx pc6
xx-xx-xx-xx-xx-xx pc7
=============================
domain3
=============================
xx-xx-xx-xx-xx-xx pc1
xx-xx-xx-xx-xx-xx pc2
xx-xx-xx-xx-xx-xx pc3
xx-xx-xx-xx-xx-xx pc4
xx-xx-xx-xx-xx-xx pc5
xx-xx-xx-xx-xx-xx pc6
xx-xx-xx-xx-xx-xx pc7
=============================
我正在尝试做这样的事情:
var = sys.argv[1]
with open('table.txt') as x:
head1 = x.readline()
linenumber = 3
if not var == head1:
for line in x.readlines(linenumber):
print line
linenumber += 1
if x.readlines(linenumber) is ('============================='):
linenumber = 16
break
以下是cmd窗口中显示的实际输出:
"readline type error an integer is required"
由于上面提到的代码块,我希望得到的输出
"xx-xx-xx-xx-xx-xx pc1"
我如何设置它以便我看到正确的数据?
答案 0 :(得分:0)
你能绕过这些线吗?
for line in x:
if 'static text' in line:
print line
答案 1 :(得分:0)
file.readlines(sizehint)
参数不是行号,请参阅the docs。
文件是Python中的行迭代器:您可以直接在for
- 循环中使用它,或者调用next()
来手动获取下一行:
with open("table.txt") as file: # open file for reading
for line in file: # read it one line at a time
line = line.strip() # remove leading/trailing whitespace
if separator == line: # found separator e.g., '====..'
line = next(line, "") # move to the next line
print line, # print the line after the separator line
break # exit the loop
根据您的输入,它将打印:
xx-xx-xx-xx-xx-xx pc1
如果文件很小,你可以将它作为一个整体读入内存并使用字符串方法解析它,例如.partition()
,.split()
,使用正则表达式(re
模块)等等例如:
import re
with open("table.txt") as file:
m = re.search(r"(?m)^=+\s*$\s*(.*)", file.read())
if m: # found
print m.group(1)
它为您的输入生成相同的输出。通常,结果可能不同,例如,正则表达式在分隔线后跳过空白行。