3

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?

2
  • will all the values on the right be valid Python literals? Strings, ints, etc.. Commented Dec 17, 2018 at 18:20
  • yes, everything that the file has on the right is either ints or floats Commented Dec 17, 2018 at 18:21

4 Answers 4

5

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
Sign up to request clarification or add additional context in comments.

5 Comments

also strip value because indentation matters for eval literal_eval(value.strip())
also why not using dict comprehension syntax?
and split_lines = map(str.strip,(line.split('=', 1) for line in inFile)) to avoid stripping key & value
That I don't follow. Won't that try to str.strip a list? (map(str.strip, line.split('=', 1)) for line in inFile) maybe, but that's a pretty busy line.
I ws trying a way to avoid applying strip on both key & values explicitly but it doesn"t matter
2

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

1 Comment

My dictionary is declared outside the function since it'll be used in other functions. Forgot to inform that in the post, my bad for that. Either way, the code is working thanks to you, thank you (and also thanks for the other tips!) !!
1

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.

Comments

0

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

2 Comments

when i print each line (after the .replace) to check if it deleted the empty spaces, it did (so thanks by that!), however when adding to the dictionary, the empty spaces "come back" lol i can have "z=1.5" in the file after using the .replace, but it still adds "z " to the dictionary, instead of only "z"
that is because you are splitting the original line named 'line', try splitting cleaned_line first_part, second_part = cleaned_line.split('=')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.