Python FileInput作为行与FileInput作为字符串
我有一个文件列表,我想用正则表达式替换来迭代这些文件,有些在单独的行上,有些需要多行匹配 我能够迭代文件列表中的行,并使用此方法写入磁盘Python FileInput作为行与FileInput作为字符串,python,regex,python-3.x,Python,Regex,Python 3.x,我有一个文件列表,我想用正则表达式替换来迭代这些文件,有些在单独的行上,有些需要多行匹配 我能够迭代文件列表中的行,并使用此方法写入磁盘 import fileinput, re ListFiles = ['in/spam.txt', 'in/eggs.txt', 'in/spam2.txt', 'in/eggs2.txt', 'in/spam3.txt', 'in/eggs3.txt', 'in/spam4.txt', 'in/eggs4.txt', 'in/spam5.txt', 'in
import fileinput, re
ListFiles = ['in/spam.txt', 'in/eggs.txt', 'in/spam2.txt', 'in/eggs2.txt',
'in/spam3.txt', 'in/eggs3.txt', 'in/spam4.txt', 'in/eggs4.txt',
'in/spam5.txt', 'in/eggs5.txt']
with fileinput.input(files=(ListFiles), inplace=True, backup='.bak') as f:
for line in f:
line = re.sub(r'this','that', line)
print(line, end='')
现在我想将f
中的输出行收集为一个字符串,我可以为其运行多行正则表达式例程
我尝试了一个带有(open)的,我已经能够使用它来与ReGex一起使用单个文件,但它不接受列表作为参数,只接受文件名
with open("spam.txt", "w") as f: # sample other use, list not allowed here.
data = f.read()
data = re.sub(r'sample', r'sample2', data)
print(data, file=f)
我试图将f
作为字符串收集到新的变量数据中,如下所示:
data = f(str)
data = re.sub(r'\\sc\{(.*?)\}', r'<hi rend="small_caps">\1</hi>', data) ## Ignore that this not multiline Regex for sample purposes only.
print(data)
data=f(str)
data=re.sub(r'\\sc\{(.*?\}',r'\1',data)##忽略此非多行正则表达式仅用于示例目的。
打印(数据)
但这会产生错误,即FileInput不可调用
有没有一种方法可以在同一with语句中迭代并将正则表达式作为行应用于文件,作为字符串应用于文件 如果可以将单个文件作为一个整体读入内存,然后在文件列表中执行多行替换,则可以一次处理一个文件:
for filename in ListFiles:
with open(filename) as file:
text = file.read() # read file into memory
text = text.replace('sample\n1', 'sample2') # make replacements
with open(filename, 'w') as file:
file.write(text) # rewrite the file
请注意,如果您只想将text1
替换为text2
,如line=re.sub(r'this','that',line)
,您只需使用line=line.replace('this','that')
。您是在文件之间进行多行匹配,还是仅在每个文件内进行多行匹配?如果是后者,为什么不遍历文件并逐个读取fileinput
只是一个方便的类,它简化了打开和读取大量文件的过程。它使用常规的open
和readline
函数。我使用的是更复杂的正则表达式,因此line.replace不够健壮。为了澄清问题,我排除了它们。J.F.塞巴斯蒂安在下面给出了一个很好的答案。非常感谢J.F.塞巴斯蒂安。作为file.input的的一个辅助命令,在与f:
中的行的相同的级别上,您解决了一个困扰我好几天的问题。现在开始写我的70多个正则表达式。