Python Forum
I don't understand the error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: I don't understand the error (/thread-11628.html)



I don't understand the error - MasterGame - Jul-18-2018

I'm a Python 2 user and made a code to filter out the vowels in a phrase. This is the code:
filtered_phrase=open("vowel_filter.txt", "w")
filtered_phrase_2=open("vowel_filter.txt", "r")
vowel_filter=raw_input("Enter text: ")
for char in vowel_filter:
  if char=="a" or char=="A" or char=="e" or char=="E" or char=="i" or char=="I" or char=="o" or char=="O" or char=="u" or char=="U":
    pass
  else:
    filtered_phrase.write(char)
new_phrase=filtered_phrase_2.read()
print new_phrase
filtered_phrase.close()
filtered_phrase_2.close()
The weird part is, when I open vowel_filter.txt (the file that contains the altered phrase) the expected phrase is there, but when I attempt to read and print the file, it won't print anything. (I indented correctly the post just doesn't save the format)


RE: I don't understand the error - gontajones - Jul-18-2018

You have to close the file first and then open it again to read.

Try this:
filtered_phrase = open("file1.txt", "w")
vowel_filter = raw_input("Enter text: ")
for char in vowel_filter:
    if char == "a" or char == "A" or char == "e" or char == "E" or char == "i" or char == "I" or char == "o" or char == "O" or char == "u" or char == "U":
        pass
    else:
        filtered_phrase.write(char)
filtered_phrase.close()
filtered_phrase_2 = open("file1.txt", "r")
new_phrase = filtered_phrase_2.read()
filtered_phrase_2.close()
print new_phrase