简体   繁体   English

在数组中逐行搜索python 2.7文件

[英]Search in files line by line python 2.7 in an array

I have a file looks like this: 我有一个文件看起来像这样:

(...)
- src: git+[server]
  name: main
  version: master

- src: git+[server]
  name: sec
  version: master

- src: git+[server]
  name: compiler
  version: master

- src: git[server]
  name: libs
  version: master

- src: git[server]
  name: crosscomp
  version: master
(...)

and I only want to change the version after 我只想在之后更改版本

name: main 名称:主要

and

name: sec 名称:秒

So my idea was to read the whole file line by line into an array and check if the line begins with the name: master or name: sec. 因此,我的想法是将整个文件逐行读取到数组中,并检查该行是否以名称:master或name:sec开头。 (with startswith() ) (带有startswith()

But how can I access the line after the finding? 但是,发现后如何进入生产线?

You can process the lines in pairs and update the next line whenever the you find a matching line. 您可以成对处理这些行,并在找到匹配的行时更新下一行。 You'll need to overwrite the contents of the file with new lines at the end. 您需要在末尾用新行覆盖文件的内容。

with open(filename, 'r+') as f:
    lines = f.readlines()

    for i in range(len(lines)-1):
        if 'name: main' in lines[i] or 'name: sec' in lines[i]:
            lines[i+1] = lines[i+1].replace('master', 'newversion')

    f.seek(0)
    f.truncate()
    f.writelines(lines)
maseterIndex = [i for i, x in enumerate(array) if x == "name: master"]
secIndex = [i for i, x in enumerate(array) if x == "name: sec"]
mergedlist = maseterIndex + secIndex
for index in mergedlist:
    #do something with next line
    print array[index+1]

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

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