0

Code:

with open ("Test1_Votes.txt", 'r'):
    f = open("Test1_Votes.txt")
    lines = f.readlines()
    print(lines[0])
    print(lines[1])
    all_lines = []

    lines = lines.rstrip("\n") #does not work
    for line in lines:
        #in here
        all_lines.append(line)
    print(all_lines)

Right now it prints outputs something like: ['1,2,3,0,0\n', ...] I would like it to output [[1, 2, 3, 0, 0], ...]

File Sample:

1,2,3,0,0

1,3,2,0,0

2,3,1,0,0

3,0,1,2,0

3,0,1,0,2

The zero's must be kept in there and there is not a blank line in between each line in the .txt

Any suggestions/answers?

Thanks in advance

Aaron
  • 10,133
  • 1
  • 24
  • 40
TIC-FLY
  • 125
  • 1
  • 10

5 Answers5

5

You have a few minor glitches in your code. The with context opens the file, so you don't need the second open statement. lines is a list of each line in your file, including the trailing '\n' characters, to remove them you can iterate over the lines list and strip off the new line characters.

with open("Test1_Votes.txt", 'r') as f:
    lines = [line.rstrip() for line in f.readlines()]
    print(lines[0])
    print(lines[1])
glglgl
  • 89,107
  • 13
  • 149
  • 217
James
  • 32,991
  • 4
  • 47
  • 70
3

You're currently stripping the new line character only from the last line of the file, if any. You should strip from each line instead:

with open ("Test1_Votes.txt") as f:
    all_lines = []
    for line in f: 
        line = line.rstrip("\n")                  # strip new line character
        lst = [int(x) for x in line.split(',')]   # split line and cast to int
        all_lines.append(lst)

Of course, you can put the entire logic into a list comprehension:

with open ("Test1_Votes.txt") as f:
    all_lines = [[int(x) for x in l.rstrip("\n").split(',')] for l in f]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Thanks for the quick reply, it seems to work well but is there a way to change each value from a string to an integer? – TIC-FLY Oct 27 '17 at 16:30
  • Thank you very much, I probably saw your question before you edited it. – TIC-FLY Oct 27 '17 at 16:34
  • I typically recommend against nested list comprehensions and one liners in general unless you're on [pcg](https://codegolf.stackexchange.com/). they can make bugs hard to find as so much is going on in a single line. – Aaron Oct 27 '17 at 16:36
1

try this

fle=open("infile.txt", "r")
lst=fle.readlines()
lst=[i.strip() for i in lst]
for i in lst:

    print i
print lst
Sandeep Lade
  • 1,865
  • 2
  • 13
  • 23
0

Use re.split() instead of readlines():

import re

your_file='abc def\nghi jkl\nmno pqr...'
all_lines=re.split('\n', your_file)
Sim Son
  • 310
  • 1
  • 10
0

A one liner might look like this:

all_lines = list([int(x) for x in line.replace('\n', '').split(',')] for line in open ("filepath", 'r').readlines())
print(all_lines)
Maor Veitsman
  • 1,544
  • 9
  • 21