![](/img/trans.png)
[英]How to read text file on python and get values from it to set it on an array
[英]read values from text file in python
我想在 python 中包含 .text 文件中的文本並將它們用作值
在文本文件中
LICENSE CODE = XXXX-XXXX-XXXX-XXXX
ACTIVATION CODE = XXXX-XXXXXXXXXXXXXXXX
在 python 中,我想使用 open() 命令讀取文件並識別許可證代碼和激活代碼並使用代碼中的值
例如,如果你的文本文件被命名為input.text
,如果你不想接觸正則表達式,我們可以按如下方式進行,
# read the file
with open("input.text", "r") as f:
for line in f:
# get LICENSE CODE
if line.strip().startswith("LICENSE CODE"):
license_code = line.strip().split(" = ")[-1]
# get ACTIVATION CODE
elif line.strip().startswith("ACTIVATION CODE"):
activation_code = line.strip().split(" = ")[-1]
else:
print("parsing in progress")
# then you can use the license code and activation code do what you want.
希望這有所幫助。
正則表達式版本:
import re
def find_regex_1(k, s):
reg = f'{k}\s*=\s*(\S+)'
return re.search(reg, s).group(1)
def read_configs(config_file):
with open(config_file, "r") as f:
content = f.read()
license_code = find_regex_1('LICENSE CODE', content)
activation_code = find_regex_1('ACTIVATION CODE ', content)
return license_code, activation_code
if __name__ == '__main__':
license_code, activation_code = read_configs('config.txt')
print(license_code, activation_code)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.