gpt4 book ai didi

Python 2.7.2 一个变量的多个值

转载 作者:太空宇宙 更新时间:2023-11-03 15:24:37 24 4
gpt4 key购买 nike

我在家经营自己的企业,2 天前开始使用 Python。我正在尝试编写一个脚本,它将逐行搜索我的日志文件并告诉我系统是否与我的强制命名方案不匹配。有多种不同的方案,我希望脚本能够找到所有方案。我试过使用列表(如下所示),但那行不通,然后我尝试使用普通括号,结果出现错误(需要左操作数,而不是元组)。我已经注意到给我带来问题的线条。

    #variables
tag = ["DATA-", "MARK", "MOM", "WORK-"] #THIS ONE!!!!!!

#User Input
print "Please select Day of the week"
print "1. Monday"
print "2. Tuesday"
print "3. Wednesday"
print "4. Thursday"
print "5. Friday"
print "6. Saturday"
print "7. Sunday"
day = input("> ")

#open appropriate file and check to see if 'tag' is present in each line
#then, if it doesn't, print the line out.
if day == 1:
f = open('F:\DhcpSrvLog-Mon.log', 'r')
for line in f:
if tag in line: #THIS ONE!!!!!!!!!!!!!
pass
else:
print line

任何提示或技巧将不胜感激!

最佳答案

我建议像这样重写代码:

with open('F:\DhcpSrvLog-Mon.log', 'rU') as f:
for line in f:
for t in tag:
if t in line: break
else:
print line

使用 with 可以在 block 退出时自动关闭文件,因此您不必担心忘记关闭它。在 for 循环中使用 else: 只会在您没有提前跳出循环时触发。

关于Python 2.7.2 一个变量的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9195185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com