Python 打开目录中的每个文本文件,然后替换每个目录中的特定行
我有一些代码可以遍历目录中的每个文件,但我需要的是遍历每个文件的特定行将替换为一个新值。有人能帮我在下面的代码中填一下缺失的空白吗Python 打开目录中的每个文本文件,然后替换每个目录中的特定行,python,Python,我有一些代码可以遍历目录中的每个文件,但我需要的是遍历每个文件的特定行将替换为一个新值。有人能帮我在下面的代码中填一下缺失的空白吗 import os line_old = '' line_new = '' for file in os.listdir("/mydir"): if file.endswith(".txt"): #something that will work, rather than the below example file.replace(
import os
line_old = ''
line_new = ''
for file in os.listdir("/mydir"):
if file.endswith(".txt"):
#something that will work, rather than the below example
file.replace(line_old, line_new)
这可能更简洁,但它会起作用
f = open(file,'r')
lines = f.readlines()
f.close()
f = open(file,'w')
for line in lines:
if line_old in line:
line = line_new
f.write(line)
f.close()
将找到所有.txt
文件,然后可以使用循环遍历每个文件的行,并将原始文件中的行替换为inplace=True
:
line_old = ''
line_new = ''
import fileinput
import sys
import glob
for line in fileinput.input(glob.iglob("/mydir/*.txt"),inplace=True):
if line.strip() == line_old:
sys.stdout.write(line_new+"\n")
else:
sys.stdout.write(line)
或写入并用于替换原始文件:
import glob
from shutil import move
from tempfile import NamedTemporaryFile
for fle in glob.iglob("./*.txt"):
with open(fle) as f,NamedTemporaryFile(dir=".",delete=False) as temp:
for line in f:
if line.rstrip() == line_old:
temp.write(line_new + "\n")
else:
temp.write(line)
move(temp.name,fle)
这假设您实际上正在更改一整行,如果您正在匹配一个特定的模式,您可以使用一个正则表达式,并且逻辑将完全相同,只需编译正则表达式并使用re.sub
import re
r = re.compile(r"\bfoo bar\b")
re.sub(line_old,line_new)
你能补充一些例子吗?你的问题不清楚,你好。我在你的答案中使用了代码的顶部部分来满足我的要求。谢谢你的帮助。
import re
r = re.compile(r"\bfoo bar\b")
re.sub(line_old,line_new)