我的代码在目录中搜索*.lis
文件并搜索aborted
-*.lis
文件
这是我的密码:
def aborted_files(file):
in_file = open(file,'r')
for lines in in_file.readlines():
if re.search("aborted", lines):
print in_file
in_file.close()
for file in os.listdir("./"):
if file.endswith(".lis"):
aborted_files(file)
我在两个文件lisfile1.lis
和lisfile2.lis
中测试它
在lisfile1.lis
中,我有aborted
,代码的结果是:
<open file 'lisfile1.lis', mode 'r' at 0x2b0edd174660>
<open file 'lisfile1.lis', mode 'r' at 0x2b0edd174660>
你能帮我只得到aborted
-*.lis
文件名吗。
我的代码中有什么不正确
如果要打印文件名,只需打印出
file.name
变量即可然后,这里不需要
re.search()
函数,只要使用in
使用
return
返回文件名比使用print
更好但是,如果在这里使用print,它将打印文件名
n
次(n
是该文件中的aborted
).readlines()
这里也没用使用
with
自动关闭文件会更简单、更安全这里有两件事
(1)打印每个匹配的文件。我猜如果
>= 1
出现'aborted'
,您可能只想打印一次文件名。 (2) 打印的是实际的文件对象,而不是文件名。另外,您只需使用with open(...)
,它将为您处理关闭文件的问题相关问题 更多 >
编程相关推荐