【问题标题】:Read and Write the specific content读写具体内容
【发布时间】:2015-06-22 02:09:52
【问题描述】:

我正在尝试读取 file1.txt 的特定内容并将此特定内容写入另一个文件 file2.txt。问题是我在 Bar 之后阅读了整个部分,我只想阅读以 [x] 开头的行并且只阅读 Bar 部分。

源代码

def read_write_file_content():
    data_file = open('file1.txt')
    block = ""
    found = False

    for line in data_file:
        if found:
            if line.strip() == "##### Foo":
                break
            else:
                block += line

        else:
            if line.strip() == "##### Bar:":
                    found = True
                    block = line
    print block




    data_file.close()

view_today()

输入文件 文件1.txt

##### Xyz
* [] Task 112
* [] Cl 221

##### Foo
* [] Task 1
* [x] Clone 2


##### Bar:
* [x] Email to A
* [] Email to B
* [x] Email to C
##### Bob
* [] Task 3
* [x] Clone Bob

输出文件 文件2.txt

##### Bar:
* [x] Email to A
* [x] Email to C

任何建议将不胜感激?谢谢:)

Subsequent question

【问题讨论】:

  • edit 添加一个具体的问题陈述——可以假设“它不起作用”,但是如何它不起作用?特征是什么错误消息或不正确的行为?
  • 是的。 [x] 位于行首。有些行是 [ ],这不是我们考虑的。

标签: python file


【解决方案1】:

通过检测部分来打开和关闭found。当foundTrue 时,过滤带有'[x]' in line 的行。

found = False

for line in open('file1.txt'):
    line = line.strip()
    if not line:
        continue
    if line.startswith('#####'):
        if line == '##### Bar:':
            found = True
            print(line)
        else:
            if found:
                break
        continue

    if found and '[x]' in line:
        print(line)

【讨论】:

    【解决方案2】:

    您首先需要检测您是否在“Bar”块内。然后,当你在的时候,打印/累积那些以* [x] 开头的行。这是一种方法:

    def get_selected_block_entries(lines, block_name,
                                   block_prefix='#####', selected_entry_prefix='* [x]'):
        selected_lines = []
    
        block_marker = '{} {}'.format(block_prefix, block_name)
        for line in lines:
            if line.startswith(block_prefix):
                in_block = line.startswith(block_marker)
                if in_block:
                    selected_lines.append(line)
            else:
                if in_block and line.startswith(selected_entry_prefix):
                    selected_lines.append(line)
    
        return selected_lines
    
    with open('file1.txt') as infile, open('file2.txt', 'w') as outfile:
        selected = get_selected_block_entries(infile, 'Bar:')
        print selected    # a list of selected entries within a Bar: block
        outfile.writelines(selected)
    

    file1.txt包含时运行上述代码:

    ##### 福 * [] 任务1 * [x] 克隆 2 ##### 酒吧: * [x] 电邮给 A * [] 电邮给 B * [x] 发邮件给 C ##### 福 * [] 任务1 * [x] 克隆 2

    打印:

    ['##### Bar:\n', '* [x] 发邮件给 A\n', '* [x] 发邮件给 C\n']

    这是从get_selected_block_entries() 函数返回的列表。同样file2.txt 包含:

    ##### 酒吧: * [x] 电邮给 A * [x] 发邮件给 C

    此输出显示未收集“栏:”块后面的选定条目。

    另请注意,如果有多个匹配块,则将从所有匹配块中收集选定条目,例如

    get_selected_block_entries(infile, 'Foo') 将返回从 两个 Foo 块中选择的条目:

    ['##### Foo\n', '* [x] Clone 2\n', '##### Foo\n', '* [x] Clone 2\n']
    

    而且,如果您想从所有块中选择 all 个选定条目,您可以这样做:

    get_selected_block_entries(infile, '')
    

    【讨论】:

      【解决方案3】:

      您可能想测试给定行是否以"* [x]" 开头。

      import re
      section = None
      for line in data_file:
          sre = re.match("^#####\s*(\w):\s*",line)
          if sre:
              section = sre.group(1)
          if line.startswith("* [x]") and section == "Bar":
                  block += line
      

      查看here 了解有关在 python 中使用正则表达式的更多信息。

      【讨论】:

      • 谢谢。但是我仍然无法获得预期的输出。问题是我在 Bar 块之后得到所有行以 * [x] 开始,我想要在 Bar 块中
      猜你喜欢
      • 2015-09-07
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多