我目前正在嘗試將 .txt 檔案中的值分成元組。這樣一來,稍后我想使用這些元組創建一個簡單的資料庫來查找資料。這是我當前的代碼:
with open("data.txt") as load_file:
data = [tuple(line.split()) for line in load_file]
c = 0
pts = []
while c < len(data):
pts.append(data[c][0])
c = 1
print(pts)
pts = []
這是文本檔案:
John|43|123 Apple street|514 428-3452
Katya|26|49 Queen Mary Road|514 234-7654
Ahmad|91|1888 Pepper Lane|
我想存盤用“|”分隔的每個值 并將這些存盤到我的元組中,以便該資料庫正常作業。這是我當前的輸出:
['John|43|123']
['Katya|26|49']
['Ahmad|91|1888']
所以它將一些資料存盤為一個字串,我不知道如何讓它作業。我想要的最終結果是這樣的:
['John', 43, '123 Apple street', 514 428-3452]
['Katya', 26, '49 Queen Mary Road', 514 234-7654]
['Ahmad', 91, '1888 Pepper Lane', ]
uj5u.com熱心網友回復:
試試這個:
with open("data.txt") as load_file:
data = [line.strip('\n').split('|') for line in load_file]
for elem in data:
print(elem)
uj5u.com熱心網友回復:
嘗試將csv模塊與自定義一起使用delimiter=:
import csv
with open("your_file.txt", "r") as f_in:
reader = csv.reader(f_in, delimiter="|")
for a, b, c, d in reader:
print([a, int(b), c, d])
印刷:
['John', 43, '123 Apple street', '514 428-3452']
['Katya', 26, '49 Queen Mary Road', '514 234-7654']
['Ahmad', 91, '1888 Pepper Lane', '']
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/535349.html
上一篇:SQL查詢格式
