Python-从文件中读取变量的值
在bash中,我有一个以可变格式存储密码的文件 e、 g 现在,如果我想使用Python-从文件中读取变量的值,python,Python,在bash中,我有一个以可变格式存储密码的文件 e、 g 现在,如果我想使用password1的值,这就是我在bash中需要做的全部工作 grep password1 file.passwd | cut -d'=' -f2 我正在寻找python中的替代方法。是否有任何库提供只提取值的功能,还是我们必须手动执行 像下面这样 with open(file, 'r') as input: for line in input: if 'password1
password1
的值,这就是我在bash中需要做的全部工作
grep password1 file.passwd | cut -d'=' -f2
我正在寻找python中的替代方法。是否有任何库提供只提取值的功能,还是我们必须手动执行
像下面这样
with open(file, 'r') as input:
for line in input:
if 'password1' in line:
re.findall(r'=(\w+)', line)
你所写的没有错。如果你想玩代码高尔夫:
line = next(line for line in open(file, 'r') if 'password1' in line)
读取文件并添加check语句:
if line.startswith("password1"):
print re.findall(r'=(\w+)',line)
代码:
import re
with open(file,"r") as input:
lines = input.readlines()
for line in lines:
if line.startswith("password1"):
print re.findall(r'=(\w+)',line)
我觉得这个很有用!使生活更轻松。line=next(line.strip().split('=')[1]用于打开的行('mout.txt',r'),如果行中有'password1',如果您只想返回密码,为什么不只是输入行的
的可能重复:
?(尽管给input
一个不同的名称,这样它就不会覆盖内置的内容了)在这里给出一个简单的方法。虽然应该使用不同的名字。不要考虑只在你的解决方案中添加链接,有容易被删除的地方。
import re
with open(file,"r") as input:
lines = input.readlines()
for line in lines:
if line.startswith("password1"):
print re.findall(r'=(\w+)',line)