简体   繁体   English

如何在python的文本文件中首先搜索有空格的行

[英]how to search lines have spaces first in text file in python

I want to search lines contain specific a string in text file.我想在文本文件中搜索包含特定字符串的行。

Example, I search lines contain strings umask 022 , not lines comment in /etc/profile file.例如,我搜索的行包含字符串umask 022 ,而不是/etc/profile文件中的行注释。

My codes:我的代码:

def check_umask(fname, umask):
   with open(fname) as f:
       return any(umask in line for line in f)
check_umask('/etc/profile','umask 022')

With code in above, but it show lines comment:使用上面的代码,但它显示行注释:

# .....
# By default, we want ... umask 022
       # bla..bla... umask 022
.........
umask 022

So, how to show only lines contain umask 022 script, not lines comment?那么,如何仅显示包含umask 022脚本的行,而不显示行注释?

You may use the combination of strip and startswith .您可以使用stripstartswith的组合。

def check_umask(fname, umask):
   with open(fname) as f:
       for line in f:
           if not line.strip().startswith('#') and 'umask 022' in line:
               print line
check_umask('/etc/profile','umask 022')

Example:例子:

>>> s = '''# .....
# By default, we want ... umask 022
       # bla..bla... umask 022
.........
umask 022'''.splitlines()
>>> for line in s:
    if not line.strip().startswith('#') and 'umask 022' in line:
        print line


umask 022
>>> 

or或者

for line in s:
    if re.search(r'^[^#]*umask 022', line):
        print line
mo = re.search(r'[^#]*umask 022', line)
if mo:
    print(mo.group())

You can use str.find() to compare indices.您可以使用str.find()来比较索引。 If a match isn't found, it returns -1, so we can turn that into a truthy/falsey value by adding 1:如果未找到匹配项,则返回 -1,因此我们可以通过加 1 将其转换为真/假值:

for line in content:
    p = line.find('#') + 1
    u = line.find('umask 022') + 1
    if u and (not p or p > u):
        print(line)

I have again the other problems with my case.我的案子又遇到了其他问题。 before "#" is a command valid.在“#”之前是一个有效的命令。

export PATH=$PATH:/... # umask 022

So, @Raj's script still show this line, althrough it contain "umask 022" in comment.所以,@Raj 的脚本仍然显示这一行,尽管它在注释中包含“umask 022”。 So, Have we solution???那么,我们有解决方案吗???

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM