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