-1
def main():
    f=open("fileread.txt","r")
    for x in f:
        p=x.split(" ")
        print(p)
main()

I have written this code for reading a matrix from a file and write it into the console. But I got unexpected output. The output should be

    ['5', '6', '9', '7']
    ['1', '7', '9', '6']
    ['4', '5', '6', '3']
    ['14', '25', '9', '6']

but I got

    ['5', '6', '9', '7\n']
    ['1', '7', '9', '6', '\n']
    ['4', '5', '6', '3', '\n']
    ['14', '25', '9', '6']

My Text file is written just like that :

5 6 9 7
1 7 9 6 
4 5 6 3 
14 25 9 6
roktim
  • 81
  • 2
  • 8
  • Does this answer your question? [How can I remove a trailing newline?](https://stackoverflow.com/questions/275018/how-can-i-remove-a-trailing-newline) – AMC Apr 05 '20 at 18:25

2 Answers2

2

\n represents a new line.

You can strip them like this:

def main():
    f=open("fileread.txt","r")
    for x in f:
        p=x.rstrip("\n").split(" ")
        print(p)
main()

I'd suggest using a csv file and Python's csv module which will handle things like this for you.

@Muts actually made a better suggestion in comment !

Caspar Wylie
  • 2,818
  • 3
  • 18
  • 32
  • 4
    You could just use `x.split()` empty strings won't be returned when separator isn't defined – Muts Apr 05 '20 at 17:51
2

Just use x.split() instead of x.split(" "). x.split() will remove multiple spaces, newlines, tabs and all other forms of whitespace.

def main():
    f=open("fileread.txt","r")
    for x in f:
        p=x.split()
        print(p)

main()

Input:

5 6 9 7
1 7 9 6
4 5 6 3
14 25 9 6

Output:

['5', '6', '9', '7']
['1', '7', '9', '6']
['4', '5', '6', '3']
['14', '25', '9', '6']
Joey
  • 1,436
  • 2
  • 19
  • 33