我正在尝试阅读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()
输入文件 FILE1.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
OUTPUTFILE FILE2.TXT
##### Bar:
* [x] Email to A
* [x] Email to C
任何建议都会非常感激?谢谢:)
答案 0 :(得分:2)
通过检测部分来打开和关闭found
。当found
True
过滤'[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)
答案 1 :(得分:1)
您可能想要测试给定的行是否以"* [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中使用正则表达式的更多信息。
答案 2 :(得分:1)
首先需要检测你是否在" 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
包含:
##### Foo * [] Task 1 * [x] Clone 2 ##### Bar: * [x] Email to A * [] Email to B * [x] Email to C ##### Foo * [] Task 1 * [x] Clone 2
打印:
['##### Bar:\n', '* [x] Email to A\n', '* [x] Email to C\n']
这是从get_selected_block_entries()
函数返回的列表。同样地,file2.txt
包含:
##### Bar: * [x] Email to A * [x] Email to C
此输出显示"栏后面的选定条目:"不收集块。
另请注意,如果存在多个匹配的块,则将从所有匹配的块中收集所选条目,例如
get_selected_block_entries(infile, 'Foo')
将从两个 Foo块中返回所选条目:
['##### Foo\n', '* [x] Clone 2\n', '##### Foo\n', '* [x] Clone 2\n']
而且,如果您想要从所有块中选择所有所选条目,您可以这样做:
get_selected_block_entries(infile, '')