我想出了下面的方法,在一行中找到一个字符串,并将该行复制到一个新文件中。我想用更动态的东西来替换Foo23
(例如[0-9],等等),但是我不能让这个或者变量或者regex工作。它没有失败,但我也没有结果。救命啊?谢谢。你知道吗
with open('C:/path/to/file/input.csv') as f:
with open('C:/path/to/file/output.csv', "w") as f1:
for line in f:
if "Foo23" in line:
f1.write(line)
Tags:
根据您的注释,每当出现任何三个字母后跟两个数字时,您都希望匹配行,例如
foo12
和bar54
。使用正则表达式!你知道吗这将匹配像
'some line foo12'
和'another foo54 line'
这样的行,但不匹配'a third line foo'
或'something bar123'
。你知道吗分解:
如果您真正需要的是将文件中的所有匹配项写入
f1
,则可以使用:本质上,您的问题归结为:“我想确定字符串是否与模式X匹配,如果匹配,则将其输出到文件”。最好的方法是使用reg-ex。在Python中,标准的reg-ex库是
re
。所以结合文件IO操作,我们有:
注意,我分割了文件IO操作以减少嵌套。我还删除了IO外部的过滤。一般来说,为了便于测试和维护,代码的每一部分都应该做“一件事”。你知道吗
相关问题 更多 >
编程相关推荐