如何将txt中的某些单词提取到Python变量中



我有一个.txt文件,用于存储cmd命令的输出。我想提取文件的某些部分,以便在Python脚本中使用它们。文本文件的内容是:

Profiles from interface  Wi-Fi:

Profiles from group directive (just reading)
---------------------------------------------
<None>
Users Profiles
-------------------
Profile from all users     : Home_Network
Profile from all users     : Work_Network
Profile from all users     : Stars_Wifi

有没有办法在Python3中使用read()write()函数,我只能将文件中的网络名称(Home_Network、Work_Network和Stars_Wifi(提取到Python脚本中的变量中?

您可以尝试将整个文件读取到一个变量中,然后使用re.findall:

text = ""
with open('path/to/file.txt', 'r') as inp_file:
text = inp_file.read()
matches = re.findall(r'Profile from all userss*:s*(S+)', text)
print(matches)
['Home_Network', 'Work_Network', 'Stars_Wifi']

最新更新