Python 2.7 Python脚本找不到文件名
以下简单脚本在当前目录中找不到文件名“We are one”。我错过了什么 非常感谢Python 2.7 Python脚本找不到文件名,python-2.7,Python 2.7,以下简单脚本在当前目录中找不到文件名“We are one”。我错过了什么 非常感谢 import re import os limit_type = re.compile('We are one|foo\.txt') #Output should have 1 file named "We are one" output = os.system("ls -1") output = str(output).split() for line in output: if limit_
import re
import os
limit_type = re.compile('We are one|foo\.txt')
#Output should have 1 file named "We are one"
output = os.system("ls -1")
output = str(output).split()
for line in output:
if limit_type.search(line, re.M|re.I):
print "Found it %s" % range_type
exit(0)
print "Not Found it!"
将正则表达式更改为
re.compile(r'weare(:?(:?one)|(:?foo))\.txt)
左括号后的:?
表示该组未捕获
正如jonrsharpe所提到的,最好使用glob
模块,而不是将ls
传递到os.system
。但是你可以自由地做你想做的事。有几件事:
- 使用r“”指定正则表达式,而不仅仅是“”
- 系统返回程序的退出值。在您的例子中,这是0,而不是程序输出。如果需要输出,请使用subprocess.Popen
- split()按空格分隔,因此您可能会有一个列表,其中有“we”、“are”和“one”,但没有短语“we are one”。使用拆分('\n')按换行符拆分
- 在打印中,您使用了不存在的变量范围\类型
import re
from subprocess import Popen, PIPE
limit_type = re.compile(r'We are one|foo\.txt')
# Run ls -1 and store stdout output
output = Popen(["ls", "-1"], stdout=PIPE).communicate()[0]
output = str(output).split('\n')
print output
for line in output:
if limit_type.search(line):
print "Found it: %s" % line
exit(0)
print "Not Found it!"
1.你到底想做什么?2.为什么您使用
os.system
调用ls
而不是使用例如os.walk
或glob
?3.作为调试的一部分,您是否尝试查看输出中的实际内容;它没有找到它;我还以为“我们是一体”的档案在那里呢。如果我将If limit_type.search(line)替换为:If re.search(r'We is one | foo\.txt',line,re.M | re.I):;然后它发现它还可以。我如何使用re.compile格式化一个模式,这样它就可以找到它了?出现以下错误:-------------------------------------回溯(最近一次调用):文件“uexample.py”,第4行,在limit\u type=re.compile(r'We are(?one | foo)\.txt)文件/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py),第190行,在编译返回文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py”的第242行中,在编译引发错误中,v#无效表达式sre#u常量。错误:模式意外结束