2

Ok so I have a .txt file wich I need to add the contents on it to a list, the problem is that there is only one character per row, for example, if I need to have "2+3", in the .txt it would look like this:

2
+
3

and then I have to add it to a list in order for it to look like this [2,+,3]

In the code I have right now it adds the contents, in string and adds up a "\n" at the end of every list element.I can't find a way to make it so that it adds the character as a int and without the \n. This is the code:

def readlist():
   count=0
   file=open("readfile.txt","r")
   list1=[]
   line=file.readlines()
   list1.append(line)
   print(list1)
   file.close

(the file is reading has 1(2+3) into it)

thanks in advance for the help

Twhite1195
  • 351
  • 6
  • 17

3 Answers3

1

The safest way is to use a try/except:

out =  []
with open("in.txt") as f:
    for line in f:
        try:
            out.append(int(line))
        except ValueError:
            out.append(line.rstrip())
print(out)

[2, '+', 3]

You don't need to strip whitespace or newline characters when casting to int, python is forgiving in that regard so we only need rstrip he new line when we catch an exception because then we have an operator.

Also with will automatically close your files, something you are actually not doing in your own code as your are missing parens to call the method file.close should be file.close()

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

This problem can be fixed with a few additions.

First every line has a \n in it's string because it's a new line in the file. To remove this you can use the rstrip method explained here very well on how it works.

From here you're going to want to convert the string into a int using int(line). This will turn the line into a integer that you can then add to your list as wanted.

The problem now is going to be choosing which line to convert into an int and which ones are arithmetic operations such as the + you have in your example file.

Community
  • 1
  • 1
-1

u can do a line.split('\n')

Sney19
  • 125
  • 1
  • 4