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:
The line number they want to update.
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’>