Python file I/O

  • 本文关键字:file Python 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!");

出于某种原因,如果一行只是"",代码似乎正在打印"警报行!我创建"if and or"结构的目的是忽略所有不包含line.find中列出的字符串的行。这里出了点问题...

如何解决此问题?

如果

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

一种更 Python 的方法(因为你不关心字符串的位置(是使用 in 运算符:

if "WECS number" in line:   # and so on

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

if line.startswith("WECS number"):

最后,只需使用括号将整个布尔表达式括起来,即可避免所有这些反斜杠。如果括号是打开的,Python 会继续转到下一行。

if (condition1 or condition2 or
    condition3 or condition4):

如果未找到字符串,则字符串find()方法返回 -1。 -1 在布尔上下文中计为 true。 因此,当您认为 if 子句不在执行时,它们正在执行。 您最好使用 if "blah" in line 来测试子字符串是否存在。

如果找不到

子字符串,str.find返回 -1,boolean(-1) == True ,因此line.find("WECS number")始终为 True,除非该行以 WECS 编号开头,在这种情况下,line.find("WECS name") 为 True。

你想要:

fPath = raw_input('File Path:')
with open(fPath) as f:
  for line in f:
    if any(s in line for s in ("WECS number", "WECS name", "Manufacturer","Type",
                               "Nominal effect", "Hub height", "x (local)",
                               "y (local)", "x (global)", "y (global)",)):
        if "y (global)" in line:
            print("Alert Line!")
        else:
            print ("Alert Last Line!")

最新更新