0

I have the following 2D array which is created from reading a file

[['1', '200', '312', '4321', '53123\n'], ['2', '234', '313', '4342', '55657\n'], ['3', '343', '454', '587\n']]

it is created using the following

def returnDocument(PROFILE):
    with open("tbs_save.txt") as textFile:
        data = [data.split(",") for data in textFile]
    print(data)

the data is stored like this

1,200,312,4321,53123
2,234,313,4342,55657
3,343,454,587

how can i remove the \n from the end of each array?

Max Thomas
  • 49
  • 8
  • Maybe you can make use of this while fetching data and making list: https://docs.python.org/3.8/library/stdtypes.html?highlight=strip#str.strip – Shashank Nov 04 '20 at 10:48
  • it would but the data is stored on a separate file with each list on a new line – Max Thomas Nov 04 '20 at 10:49

2 Answers2

1

I suggest to use strip() for each line of the text file to remove the trailing '\n'.

data = [data.strip().split(",") for data in textFile]

Alternatively, since your file contains integers, you could convert each entry to an integer in the list comprehension. Integer conversion will get rid of the '\n' as well.

data = [list(map(int, data.split(","))) for data in textFile]
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
0

It looks like you works with the csv-files, so you can use the csv.reader to work with the data in a more convenient way. For example:

import csv

def return_document():
    with open("tbs_save.txt") as csv_file:
        reader = csv.reader(csv_file, delimiter=",")
        data = [row for row in reader]
    print(data)

For the provided data example, to output will be:

[['1', '200', '312', '4321', '53123'], ['2', '234', '313', '4342', '55657'], ['3', '343', '454', '587']]

Also, the csv.reader usage allows you to avoid some bugs, for example in case when somebody will put spaces after commas in some files