Reputation: 33
Hi I've got a question about my code:
def mata_in_resultat():
with open('file.txt', 'r+') as f:
data = [[int(value) for value in line.strip().split()] for line in f ]
f.seek(0)
i = int(input("Add your result to column! \n"))
j = int(input("Add your result to row! \n"))
data[i][j] += 1 # Assign to the index of the column and row
for line in data:
f.write(' '.join(map(str, line)) + "\n")
f.truncate()
print(data)
The code does that it opens the file.txt that contains for example:
0 0 0 0
0 0 0 0
0 0 0 0
Choosing a specific value in a column and a row for example i=0 j=0
manipulates the file and saves the new information (deletes the old info)
1 0 0 0
0 0 0 0
0 0 0 0
My question is; how do I link a name to each row (horizontal lines) in the file, for example:
1. having the name in the file, being able to continue to change specific values as before:
Pear 1 0 0 0
Apple 0 0 0 0
2. or somehow linking each row (horizontal line) to a name in a separate file
When I do this to my current file the message:
ValueError: invalid literal for int() with base 10: 'Apple'
shows up!
Upvotes: 0
Views: 51
Reputation: 2689
probably the quickest hack to add that to your existing code is to change this line:
data = [[line.strip().split()[0]] + [int(value) for value in line.strip().split()[1:]] for line in f ]
and also:
data[i][j + 1] += 1 # Assign to the index of the column and row
what I'm doing there is only int
ing the numbers in the row, and then moving the input one column to the right to account for the extra column that you've added.
you might be interested in using something like pandas
to do this.
you could do something like
import pandas as pd
data = pd.read_csv('file.txt', sep=' ', header=None)
data.columns = ['name', '1', '2', '3', '4']
j = int(input("Add your result to column! \n"))
i = int(input("Add your result to row! \n"))
data.loc[i, j] = data.loc[i, j] + 1
# this maybe should be
# data.ix[i, j] = data.ix[i, j] + 1
# i don't really use integer indexing so i'm not 100%
data.to_csv('file.txt', sep=' ', index=None)
Upvotes: 1