0

我有一个非常简单的 python 脚本,它读入一个文件,并逐行解析它。

它似乎无法识别我行首的“//”。如果我将其更改为在行首查找“#”,它也找不到这些行。我只是误解了这一点吗?

line = fIn.readline()

while line:
    print "line is", line
    line = line.strip()
    if line.startswith('//'):
        print "winner"
    line = fIn.readline()

我正在阅读的文件如下所示:

// Feedback
"Feedback" = "Feedback";

// New strings
"File URL not reachable." = "File URL not reachable.";

打印出来的调试行看起来很合适:

line is // Feedback

line is "Feedback" = "Feedback";

line is 

line is // New strings

line is "File URL not reachable." = "File URL not reachable.";

line is 
4

3 回答 3

1

更好的版本:

with open("abc") as f:
    for line in f:
        line=line.strip()
        if line and line.startswith("//"):
            print "line is",line
            print "winner"
            print next(f)
   ....:             

输出:

line is // Feedback
winner
"Feedback" = "Feedback";

line is // New strings
winner
"File URL not reachable." = "File URL not reachable.";
于 2013-04-16T21:40:47.610 回答
0

您只阅读文本文件的一行。除了你在最后一行有错误的缩进之外,它似乎有效。在确保line = fIn.readline()每次迭代都执行之后尝试运行您的程序(将其向左移动一个块)。

这是修复那条线后得到的结果,这是所需的输出吗?

line is // Feedback

winner
line is "Feedback" = "Feedback";

line is  

line is // New strings

winner
line is "File URL not reachable." = "File URL not reachable.";

编辑:这对你有用吗?

for line in open("yourfile.txt").readlines():
    print "line is", line
    line = line.strip()
    if line.startswith('//'):
        print "winner"
于 2013-04-16T21:38:13.067 回答
0

尝试这个

for line in fIn:
    print "line is", line
    line = line.strip()
    if line[0:2]=='//':
        print "winner"
        line = fIn.readline()
于 2013-04-16T21:41:44.380 回答