【问题标题】:How do I copy from keyword to keyword in Python 2.7?如何在 Python 2.7 中从关键字复制到关键字?
【发布时间】:2017-06-08 21:44:53
【问题描述】:

如何在 Python 2.7 中将一个文件 fileA 中的行关键字逐个关键字复制到另一个文件 fileB 中?查询应在输出中包含关键字。

【问题讨论】:

  • 你想复制一个文件到另一个?

标签: python-2.7 file io


【解决方案1】:

如果您的问题是复制 startWord 和 endWord 之间的原始文件的一部分,您可以使用此文件,该文件稍作修改 Extract subset of file in bash or Python

begin = 'BEGINSTRING'
end = 'ENDSTRING'

with open(f, 'r') as input_file:
  tmp = []
  flag = False

  for line in input_file.readlines():

    if begin in line:            
      flag = True
      index = line.find(begin)
      tmp.append(line[index:])
      continue
    elif flag:
      tmp.append(line) 
    elif end in line:
      index = line.find(end)             
      tmp.append(line[:index+1]) 
      break
    else:
      pass

with open(f + '_new', 'w') as output_file:
  for line in tmp:
  output_file.write(line)

【讨论】:

  • 如果我想添加 strip(),开始和结束...我该怎么做?我正在寻找一个准确的短语。
  • @CookiesMonster 我不完全明白你想在什么上使用 strip()。如果您想将它用于开始和结束词,您可以在第 1 行和第 2 行使用它,即 begin = 'BEGINSTRING'.strip() 和 end..... 类似。如果您想从文件的最终子集中删除字符,您可以在 for 循环之后和写入新文件之前使用 tmp.strip()。
  • 太完美了。 :) 唯一的是......即使我这样做,它也无法识别结束字符串: ENDSTRING.strip() ?新文件只是原始文件的副本? IE:它与结束字符串不匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2020-02-16
相关资源
最近更新 更多