Python文件I/O.

Eae*_*Eae 0 python io

fPath = raw_input('File Path:')
counter = 0;
flag = 0;

with open(fPath) as f:
    content = f.readlines()

for line in content:
    if flag == 0 and line.find("WECS number") or \
    line.find("WECS number") or \
    line.find("WECS name") or \
    line.find("Manufacturer") or \
    line.find("Type") or \
    line.find("Nominal effect") or \
    line.find("Hub height") or \
    line.find("x (local)") or \
    line.find("y (local)") or \
    line.find("x (global)") or \
    line.find("y (global)"):

        if not line.find("y (global)"):
            print ("Alert Last Line!");
        else:
            print("Alert Line!");
Run Code Online (Sandbox Code Playgroud)

由于某种原因,代码似乎是打印"警报线!" 如果一行只是"\n".我创建"if和or"结构的意图是忽略所有不包含line.finds中列出的字符串的行.这里出了点问题......

我该如何解决这个问题?

kin*_*all 6

如果找不到子字符串,则.find()返回字符串的方法-1.-1是非零的,因此被认为是真的.这可能不是你所期望的.

一个更Pythonic方式(因为你不关心字符串的位置)是使用in运算符:

if "WECS number" in line:   # and so on
Run Code Online (Sandbox Code Playgroud)

您还可以使用startswith()并endswith()在适当情况下:

if line.startswith("WECS number"):
Run Code Online (Sandbox Code Playgroud)

最后,只需使用括号括起整个布尔表达式,就可以避免所有这些反斜杠.如果括号打开,Python会继续前进到下一行.

if (condition1 or condition2 or
    condition3 or condition4):
Run Code Online (Sandbox Code Playgroud)

  • 我可能会写`phrase =("WECS number","WECS name")`然后`if if(短语中的短语),而不是链接所有那些`或`.如果它真的是"startwith",那就更好了:`line.startswith(短语)`. (2认同)