How do I add the nth element for every line in a text file?

Suppose I have a text file, in this format:

1 1 1 1 1 99.5016 10.43 99.5016 99.5016 7.074 47.8012 10.43 7.074 7.074
2 1 1 1 1 99.5016 10.43 99.5016 99.5016 7.074 47.8012 10.43 7.074 7.074
3 1 1 1 1 99.5016 10.43 99.5016 99.5016 7.074 47.8012 10.43 7.074 7.074


And I want to add up all the elements in the ones column, for a certain number of lines. How would I do that?

I have this currently:

data = Import[
"/Users/myname/Documents/foldername/filename.txt", "Table"]
Total@data[[All, 2]];


You need Import, Part (i.e. [[...]]), probably Span (i.e. ;;), and Total.

Import the data:

data = Import["path\to\yourdatafile.txt", "Table"];


Sum all entries in the first column:

Total@data[[All, 1]]


Sum entries in the third column and in the second to third row:

Total@data[[2 ;; 3, 3]]


Sum entries in column 2, rows 1 and 3:

Total@data[[{1, 3}, 2]]

• I believe I did everything you mentioned, but it doesn't produce an output. data=Import["textfile", "Table"]; Total@data[[2;;10000,2]]; (If I wanted to add up everything in the second column) – Ihaveaquestion May 11 '16 at 19:53
• @Ihaveaquestion Well, I took your sample data and copied in a text file, then ran the code exactly as shown, just substituting the correct path, and obtained these results. I suspect that perhaps the format of the file is not as you expect it, or the numbers are not stored in a simple form. Could you share the exact contents of your data file? – MarcoB May 11 '16 at 19:55
• There are 10k lines in my text file, so I don't think I can fit that here. The elements in each line are separated by a single space, and each line has 13 elements. – Ihaveaquestion May 11 '16 at 19:55
• @Ihaveaquestion Then perhaps you could show the first few here, just to make sure of format, then provide a link to the whole file (pastebin, filetea, dropbox, github, etc). – MarcoB May 11 '16 at 19:56
• replaced original question's lines with 3 actual lines from my file – Ihaveaquestion May 11 '16 at 19:57

I figured it out.

data = Import[
"/Users/myname/Documents/foldername/filename.txt", "Table"]
Total[data, {1}]


Part of the error was that I had an empty row at the end of my text file.