Home > Mobile >  How to read file with lines of integers separated by a comma to a list without "\n"
How to read file with lines of integers separated by a comma to a list without "\n"

Time:10-05

I am a new to the os module

I've been stuck for hours on this question and I really would appreciate any type of help:)

I have a file that contains 6 lines where each line has 6 numbers separated by a comma. What I want to do is to get all of these numbers into a list so that I later can convert them from str to int. My problem is that I can't get rid of "\n". Here is my code

Thank you

CodePudding user response:

def read_integers(path):
    content_lst=[]
    with open(path,'r') as file:
        content=file.read()
        for i in content.split('\n'):
            content_lst =i.split(', ')
        return content_lst

CodePudding user response:

Your file actually has multiple lines (in addition to the comma separated numbers). If you want all the numbers in a single "flat" list you'll need to process both line and comma separators. One way to do it simply is to replace all the end of line characters with commas so that you can use split(',') on a single string:

with open(path,'r') as file:
    content_lst = file.read().replace("\n",", ").split(", ")

You could also do it the other way around and change the commas to end of lines. Converting the values to integers can be done using the map function:

with open(path,'r') as file:
    content_lst = file.read().replace(",","\n").split()
    content_lst = list(map(int,content_lst))
  • Related