假设Linux中有一个示例文本文件
[SampleText.txt] 1234 = 1234 abcd = 1234 efgh = /home/user/targetfile1.txt ijkl = /home/user/targetfile2.txt
如何从SampleText.txt中获取特定路径(/home/user/targetfile1.txt& /home/user/targetfile2.txt)并将其放在变量中?
答案 0 :(得分:1)
答案 1 :(得分:1)
我建议的方法是将文件解析为常规配置文件,并存储看起来像赋值的内容。如果你的文件中还有其他奇怪的东西,这可能不起作用,但我认为它可以在这里工作。
myvars = {}
# iterate through all the lines
for line in open('SampleText.txt').readlines():
# skip this line if it doesn't look like an assignment
if not '=' in line: continue
# split it into left and right pieces
left, right = line.split('=', 1)
# keep it around in a dictionary
myvars[left.strip()] = right.strip()
# now you can query it to get stuff:
myvars['efgh'] # returns /home/user/targetfile1.txt