[英]Python file I/O
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!");
由於某種原因,該代碼似乎正在打印“ Alert Line!”。 如果一行只是“ \\ n”。 我創建“ 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()
字符串,則字符串find()
方法將返回-1。 -1在布爾上下文中算作true。 因此,當您認為if子句不執行時,它們就會執行。 您最好if "blah" in line
使用if "blah" in line
來測試子字符串是否存在。
如果找不到子字符串, str.find
返回-1,並且boolean(-1) == True
,所以line.find("WECS number")
始終為True,除非行以line.find("WECS number")
開頭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!")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.