我有一个类似这样的文件(我使用的是fstab的副本作为文件):
# <file system> <dir> <type> <options> <dump> <pass>
UUID=121231414142 /media/data ntfs3 defaults 1 1
UUID=2321231414142 /media/data2 ntfs-3g defaults 1 1
UUID=451231414142 /media/data3 ntfs3 defaults 0 0
UUID=455612314141 /media/videodisk ntfs3 defaults 0 0我想要的是通过给出挂载点(例如/media/data)来查找一行,并在这一行上替换模块(如果是ntfs3到ntfs-3g,如果是ntfs-3g到ntfs3)
我试过这个:
with open(filepath, "r") as file:
lines = file.read()
if (mountpoint + " ntfs-3g") in lines:
print("ntfs-3g")
lines=lines.replace(mountpoint + " ntfs-3g", mountpoint + " ntfs3")
elif (mountpoint + " ntfs3") in lines:
lines = lines.replace(mountpoint + " ntfs3", mountpoint + " ntfs-3g")
print("ntfs3")
print(lines)但是这也用data2和data3代替了行。那么,如何只替换特定的行,以及如何将更改后的字符串写回文件?
发布于 2022-07-31 14:28:10
我会做一个regex搜索-使用函数替换
import re
with open(filepath, "r") as file:
lines = file.read()
def swap(match):
mount, driver = match.group(1), match.group(2)
replaces = {
"ntfs-3g" : "ntfs3",
"ntfs3" : "ntfs-3g",
}
new_driver = replaces[driver]
# error out if the driver is not expected
return f"{mount} {new_driver}"
lines = re.sub(f"({mountpoint})\W+([a-zA-Z0-9_-]+)", swap, lines)
print(lines)基本上是一个简单的正则表达式,与挂载点+空白空间+驱动程序组合相匹配,将它们传递给创建替换字符串的函数。
编辑
编辑代码,将\w+替换为[a-zA-Z0-9_-]+,因为\w不包括破折号。
https://stackoverflow.com/questions/73182881
复制相似问题