Delete space when reading a text in python

0

I'm having problems reading a file, it's a vector with a series of numbers, I want to operate with that data, but when I read it, it adds a "\ n" line break that is not in my text file, I am using the following code:

infile=open('uncarb.txt')
x=infile.read()
print(x)
infile.close

Any help will be welcome, thanks.

    
asked by Raymundo Torres 28.07.2017 в 00:38
source

3 answers

0
infile=open('uncarb.txt')
x=infile.read()
print(x),
infile.close

You have to add one, at the end of print to avoid the line break

    
answered by 28.07.2017 в 01:00
0

The print of Python adds a line break: \n . A good solution is to use another tool that I did not add. I also advise you to use with which is a context-manager that automatically takes care of closing the file when you exit the code block (in this way obvious the close )

import sys

with open("uncarb.txt") as infile:
    for line in infile:
        sys.stdout.write(line)
    
answered by 28.07.2017 в 22:46
0

It is not clear if, as you say in the question, you add a line break when reading the file, or if, as other users have answered, the line break occurs > when printing what you have read.

Since nobody has yet answered how to solve it if it were the first case ( to read ), I add this answer. The screenshot that you include does not help much either, since you can not clearly see where that extra car return you mentioned would be.

The method .rstrip() of the chains is used to eliminate spaces or carriage returns that the chain may contain at the end. You also have .lstrip() to delete the ones you can contain at the beginning and .strip() for both sides at the same time. Therefore:

with open('uncarb.txt') as infile:
    x=infile.read().strip()
print(x)

And by the way, although you did not ask this, it seems that what you read from the file is a string that contains the ASCII representation of a list (perhaps JSON). Since you say that then you are going to process that data, you will need to convert it to a list of python numbers. In this case you can do:

lista = eval(x)

Or, if you prefer not to take security risks (you do not trust that the content of the file you are reading may contain dangerous python code that would be executed as part of eval() ), you can remove the brackets that delimit the list and then Separate it by commas, like this:

x = x.replace("[", "").replace("]", "")
lista = [ int(n) for n in x.split(",") ]
    
answered by 24.09.2018 в 12:56