Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete empty spaces of files python

I have a file with several lines, and some of them have empty spaces.

x=20
y=3
z = 1.5
v = 0.1

I want to delete those spaces and get each line into a dictionary, where the element before the '=' sign will be the key, and the element after the '=' sign will be its value.

However, my code is not working, at least the "delete empty spaces" part. Here's the code:

def copyFile(filename):
    """
    function's contract
    """
    with open(filename, 'r') as inFile:
        for line in inFile:
            cleanedLine = line.strip()
            if cleanedLine:
                firstPart, secondPart = line.split('=')  
                dic[firstPart] = float(secondPart)
        inFile.close()
    return dic

After clearing the empty spaces, my file is supposed to get like this

x=20
y=3
z=1.5
v=0.1

But is not working. What am I doing wrong?

like image 510
Slifez Avatar asked Jun 22 '26 13:06

Slifez


1 Answers

You need to strip after splitting the string. That's assuming that the only unwanted spaces are around the = or before or after the contents of the line.

from ast import literal_eval

def copyFile(filename):
    with open(filename, 'r') as inFile:
        split_lines = (line.split('=', 1) for line in inFile)
        d = {key.strip(): literal_eval(value.strip()) for key, value in split_lines}
    return d
like image 126
Patrick Haugh Avatar answered Jun 24 '26 01:06

Patrick Haugh