Write to the file not working

MyFavoriteColors content:
red
yellow
green
blue

Prob:
Replace a single line

If the user wants to replace a single line in the file, they will then need to be prompted for 2 bits of information:

  1. The line number they want to update.

  2. The text that should replace that line.

         x = int(input("Enter line number to change: "))
         y = input("Enter color: ")
    
         BrightColor = open("MyFavoriteColors", "r")
         lines = BrightColor.readlines()
         lines[x] = y
         print(lines)
         BrightColor.close()
    

#Write content of line to the file

         BrightColor = open("MyFavoriteColors", "w")
         BrightColor.writelines(lines)
         print(BrightColor)
         BrightColor.close()
  • I received the below error once I attempt to write to the file. My assumption is that when you use “w” to write to the file, the file will be emptied, am I correct on this? If it is, i still have the contents from the variable lines, why i cannot write it to the file?

Enter selection: D
Enter line number to change: 1
Enter color: white
[‘red\n’, ‘white’, ‘green\n’, ‘blue\n’]
<_io.TextIOWrapper name=‘MyFavoriteColors’ mode=‘w’ encoding=‘cp1252’>

There is no error.

BrightColor is a file, wrapped in an object which takes care of writing it. When you print it, you get its repr, the description the programmer found useful for other programmers.

So it is an _io.TextIOWrapper, named MyFavoriteColors and you opened it for writing. What is not to like :slight_smile:

To see the content, print lines.

Hi Oliver,

yes, as far as I remember, it is correct, that with “w” you have chosen to “overwrite” an existing file.

As Menno already pointed out, the line “<_io.TextIOWrapper name=‘MyFavoriteColors’ mode=‘w’ encoding=‘cp1252’>” does not look like an error message. It seems to just be the result of the

.

You normally can identify error messages by the term “exception” in them…

Cheers, Dominik

so this means, my code is working fine?

Thanks

If the file content (after your code has been executed) is fine (did you check, whether all lines have the same line ending/break “\n” or alike? Otherwise have a look at os.linesep), your code seems to be fine.

You just might want to consider using the with statement alike:

with open("MyFavoriteColors", "r") as BrightColor:
       lines = BrightColor.readlines()
       ...

You do not need to close the file then - the “with”-block takes care for that. Such a “with” block is preferable, as it takes care of closing even in case of exceptions.

You are welcome :slight_smile:

Cheers, Dominik