使用 if 条件的迭代在 python 中不起作用
Iteration with if condition not working in python
我写了下面的脚本
#! /usr/bin/python
import glob
path = raw_input('In which dir do you want to look for the files?')
path += '/*.txt'
files=glob.glob(path)
for seq in files:
f=open(seq)
total = 0
for line in f:
if 'NAR' in line:
print("bum")
f.close()
所以如果我有这样的文件:
NAR 56 rob
NAR 0-0 co
FOR 56 gs
FRI 69 ds
NIR 87 sdh
我希望我的代码能够打印
bum bum
然后我在阅读后尝试了以下内容 here
#! /usr/bin/python
import glob
path = raw_input('In which dir do you want to look for the files?')
files=glob.glob(path)
for seq in files:
with open(seq) as input_file:
for line in input_file:
if 'NAR' in line:
print("bum")
input_file.close()
但两者都不行。我在这里做错了什么?
如果 path
确实是现有目录的路径,没有通配符,那么 glob.glob
将 return 仅包含该目录的单项列表。
您可能希望在 glob.glob
调用之前添加类似
的内容
if not path.endswith('*'):
path = os.path.join(path, '*')
或者更一般地说,您的情况可能是:
if '*' not in path:
尽管如果您对任何地方的通配符都满意,但如果缺少通配符则不清楚要添加到哪里。
您的 files
列表仅包含目录,不会查找写入的文件。例如,如果您要匹配 txt
个文件,则需要说
path += '\*.txt'
因此 glob
查找 txt
文件。而不是
'C:\folder\folder'
搜索将是
'C:\folder\folder\*.txt'
我写了下面的脚本
#! /usr/bin/python
import glob
path = raw_input('In which dir do you want to look for the files?')
path += '/*.txt'
files=glob.glob(path)
for seq in files:
f=open(seq)
total = 0
for line in f:
if 'NAR' in line:
print("bum")
f.close()
所以如果我有这样的文件:
NAR 56 rob
NAR 0-0 co
FOR 56 gs
FRI 69 ds
NIR 87 sdh
我希望我的代码能够打印
bum bum
然后我在阅读后尝试了以下内容 here
#! /usr/bin/python
import glob
path = raw_input('In which dir do you want to look for the files?')
files=glob.glob(path)
for seq in files:
with open(seq) as input_file:
for line in input_file:
if 'NAR' in line:
print("bum")
input_file.close()
但两者都不行。我在这里做错了什么?
如果 path
确实是现有目录的路径,没有通配符,那么 glob.glob
将 return 仅包含该目录的单项列表。
您可能希望在 glob.glob
调用之前添加类似
if not path.endswith('*'):
path = os.path.join(path, '*')
或者更一般地说,您的情况可能是:
if '*' not in path:
尽管如果您对任何地方的通配符都满意,但如果缺少通配符则不清楚要添加到哪里。
您的 files
列表仅包含目录,不会查找写入的文件。例如,如果您要匹配 txt
个文件,则需要说
path += '\*.txt'
因此 glob
查找 txt
文件。而不是
'C:\folder\folder'
搜索将是
'C:\folder\folder\*.txt'