delete empty spaces of files python

Viewed 402

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?

4 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

There are a few issues with your code.

For one, you never define dic so when you try to add keys to it you get a NameError.

Second, you don't need to inFile.close() because you're opening it in a with which will always close it outside the block.

Third, your function and variable names are not PEP8 standard.

Fourth, you need to strip each part.

Here's some code that works and looks nice:

def copy_file(filename):
    """
    function's contract
    """
    dic = {}
    with open(filename, 'r') as in_file:
        for line in in_file:
            cleaned_line = line.strip()
            if cleaned_line:
                first_part, second_part = line.split('=')
                dic[first_part.strip()] = float(second_part.strip())
    return dic

You have two problems:

  1. The reason you're not removing the white space is that you're calling .strip() on the entire line. strip() removes white space at the beginning and end of the string, not in the middle. Instead, called .strip() on firstpart and lastpart.

  2. That will fix the in-memory dictionary that you're creating but it won't make any changes to the file since you're never writing to the file. You'll want to create a second copy of the file into which you write your strip()ed values and then, at the end, replace the original file with the new file.

to remove the whitespace try .replace(" ", "") instead of .strip()

Related