簡體   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