0
我有一個csv文件,每隔10秒添加一個新的結果。每一個(從用戶指定)我讀這個csv並製作一個JSON文件。我不想每次都將整個csv轉換爲JSON,而只是將最後一部分更新。所以,我想我會每次保留最後一行,然後我將開始從這一行讀取文件,然後將其轉換爲JSON格式。只讀Python中csv文件的更新部分
myJson = {}
try:
with open('myFile.csv', 'r') as f: #Read the csv file with read privileges.
for line in f:
lst = re.split(r' +', line.rstrip('\t')) #Columns are seperated with tabs.
if len(lst) == 3: #There are three columns in the file:
n = lst[0].strip() #Names
v = lst[1].strip() #Values
p = lst[2].strip() #Percentages
try:
myJson[n].append(v) #Add values to the according keys.
except KeyError:
myJson[n] = [v] #Handle potential KeyErrors.
except IOError:
print "csv file has not been created yet."
最簡單的方法是,在每次刪除CSV文件,但它會更加有用,我要保持它,只是創造新的JSON文件。
看看https://stackoverflow.com/questions/12523044/how-can-i-tail-a-log-file-in-python – 2016-05-31 14:03:42
也許你應該考慮用一個實際的數據庫替換該csv文件。 – Ulisha