我有一個 .txt 檔案,如下所示:
'192.168.0.1','sarah','privatepassword'
'192.168.20.2','john','password1'
如何獲取檔案的行并將它們分配給 ip、用戶名和密碼的變數?如果需要,我可以更改 .txt 檔案的格式。
uj5u.com熱心網友回復:
試試下面的代碼。
首先打開 .txt 檔案,然后回圈遍歷每一行。然后,您可以使用變數ip、name和pwd來保存檔案每一行中的元素。
f = open(r'test.txt' , 'r')
for x in f:
x=x.rstrip()
x = x.split(',')
ip,name, pwd = x
print(ip)
print(name)
print(pwd)
uj5u.com熱心網友回復:
all_creds = []
with open("separate.txt", "r") as creds:
creds = myfile.readline()
while creds:
ip, un, pw = creds.split(',')
all_creds.append((ip, un, pw))
creds = myfile.readline()
print(all_creds)
uj5u.com熱心網友回復:
您可以使用split()并將結果存盤在串列中
a = []
s = "'sarah','192', 'pass'"
a.append(s.split(","))
a現在是一個包含三個元素串列的串列。
[["'sarah'", "'192'", " 'pass'"]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/444823.html
