我想打印针对同一个文件运行的两个正则表达式的输出。
我试过了
import re
with open("C:\\Users\\frank\Documents\\file-with-digits.txt") as myfile:
print(re.findall(r'organizationID as int\s*=\s*(\d+)', myfile.read()))
print(re.findall(r'organizationID\s*=\s*(\d+)', myfile.read()))
和
import re
with open("C:\\Users\\frank\Documents\\file-with-digits.txt") as myfile:
print(((re.findall(r'organizationID as int\s*=\s*(\d+)', myfile.read())), re.findall(r'organizationID\s*=\s*(\d+)', myfile.read())))
在每种情况下,第二个打印语句都没有显示输出。
如果我分别运行它们,它们都会显示其独特的输出。如何组合它们以便我看到两个正则表达式的输出?我当然可以打开文件两次并单独运行它们,但我认为必须可以将它们组合起来。
答案 0 :(得分:2)
这应该可以回答您的问题:Why can't I call read() twice on an open file?
在您的具体情况下,您想要做的是:
import re
with open("C:\\Users\\frank\Documents\\file-with-digits.txt") as myfile:
file_contents = myfile.read()
print(re.findall(r'organizationID as int\s*=\s*(\d+)', file_contents ))
print(re.findall(r'organizationID\s*=\s*(\d+)', file_contents ))
此外,根据经验:读取文件等 I/O 操作通常很慢。因此,即使对文件调用两次 read()
会产生您预期的效果,最好只调用一次并将结果存储在变量中,以便您可以重复使用它。