假设示例文件“ data.txt”,其中:
NAME COLOR INDEX DEBIT
Leo blue 1 40
Mike orange 2 55
Don purple 3 32
Raph red 4 21
如果我需要找到Leo并把他的债务加成12,那是最好的方法?
我试图弄清楚我该如何做,例如,检查“如果user [name]在用户中”。
我已经完成了:
data = open('data.txt','r')
index = data.readline().split()
index1 = index[0]
index2 = index[1]
index3 = index[2]
index4 = index[3]
users = list()
for line in data.readlines():
value = line.split()
user = dict()
user[index1] = value[0]
user[index2] = value[1]
user[index3] = value[2]
user[index4] = value[3]
users.append(user)
print(users)
我在哪里创建字典并将其添加到列表中。
我需要更改原始存档,以将新值加到列借方中。
顺便说一句,非常感谢您的帮助。我正在独自学习如何使用python操作文件。 :)
答案 0 :(得分:1)
如果您想使用熊猫,可以这样做
df = pd.read_csv('file.txt', sep=" ", header=None)
df.columns = ["name", "color", "index", "debit"]
index = df[df['name']==name].index
df.loc[index,'debit']+=12
答案 1 :(得分:1)
import pandas as pd
df = pd.read_csv('data.txt', sep='\t', index_col='NAME')
df.loc['Leo','DEBIT']+=12
答案 2 :(得分:0)
如果您想走已经走的路...您可以尝试以下方法:
names = [i['NAME'] for i in users] #get list of names
keys = users[0].keys() #get list of keys
name = 'Leo' #name of entry to change
loc = names.index(name) #location of this entry in the original list "users"
for u in users: #convert numbers to floats so you can add to them (or int works)
for k in keys:
try:
u[k]=float(u[k])
except:
pass
users[loc]['DEBIT']+=12 #finally, add desired value to this entry
熊猫很容易,但是如果您正确读取文件