繁体   English   中英

从文件中的一行读取特定字符串

[英]Reading Specific String from a line in a file

我有这样的文件:

face LODRxERROR
{
  source   R/com/int/LRxAMEexception.csv

  contains R/saqf/LAWODRxERROR.ddf
  contains R/bld/LAWODRxERRORtyp.h
  contains R/bld/LAWODRxERRORtyp.hpp

  requires LAWODRxERR
}

目前,我能够读取并存储特定行。 但我需要更具体。 而不是阅读整行。 我只想读取文件名而不是目录。 因此,我LAWODRxERRORtyp.hpp读取LAWODRxERRORtyp.hpp ,而不是读取R/bld/LAWODRxERRORtyp.hpp LAWODRxERRORtyp.hpp

到目前为止,这是我的python代码:

    with open(file) as scope:
        for line in scope:
            line = line.strip()
            if line.startswith('contains') and line.endswith('.h') or line.endswith('.hpp'):
                scopeFileList.append(line.split()[-1])

提前致谢

您可以使用内置函数os.path.basename()从路径中仅获取文件名:

from os.path import basename

with open(file) as scope:
    for line in scope:
        line = line.strip()
        if line.startswith('contains') and line.endswith('.h') or line.endswith('.hpp'):
            path = line.split()[-1]
            scopeFileList.append(basename(path))

尝试这个,

with open("file1.txt", "r") as f:
    data = [line.replace("\n","").split('/')[-1] for line in f.readlines() if '.' in line]

输出:

print(data)

['LRxAMEexception.csv',
 'LAWODRxERROR.ddf',
 'LAWODRxERRORtyp.h',
 'LAWODRxERRORtyp.hpp']

试试这个:您可以使用re.search从路径中找到文件名

with open('new_file.txt') as file:
     for line in file:
             line = line.strip()
             if line.startswith('source') or line.startswith('contains'):
                    file_names = re.search('/(.+?)\/((\w+)\.\w+$\Z)', line).group(2)
                     print(file_names)

O / P:

'LRxAMEexception.csv'
'LAWODRxERROR.ddf'
'LAWODRxERRORtyp.h'
'LAWODRxERRORtyp.hpp'

暂无
暂无

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

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