简体   繁体   English

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

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

I have file looking like this: 我有这样的文件:

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
}

At the moment I'm able to read a specific line and store it. 目前,我能够读取并存储特定行。 But I need to be more specific. 但我需要更具体。 Instead of reading the whole line. 而不是阅读整行。 I would like to read only the file name no the directory. 我只想读取文件名而不是目录。 So, instead of reading R/bld/LAWODRxERRORtyp.hpp I would like to read only LAWODRxERRORtyp.hpp 因此,我LAWODRxERRORtyp.hpp读取LAWODRxERRORtyp.hpp ,而不是读取R/bld/LAWODRxERRORtyp.hpp LAWODRxERRORtyp.hpp

Here is my python code so far: 到目前为止,这是我的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])

Thanks in advance 提前致谢

You can use the built-in function os.path.basename() to get only the file-name from a path: 您可以使用内置函数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))

Try this, 尝试这个,

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

Output: 输出:

print(data)

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

Try this: You can use the re.search to find the file names from a path 试试这个:您可以使用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: O / P:

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

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

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