Your code is correct, the error occurs because your directory is an invalid/nonexistent directory, try to use the complete directory like:
'C:/Users/Username/Desktop/Folder/filename.txt'
For opening file:
file = open(directory, flag)
Main flags (modes) are:
"r"
for reading text, throws an exception if the file doesn't exist
"rb"
for reading bytes, throws an exception if the file doesn't exist
"w"
for writing text, doesn't throw an exception if the file doesn't exist, but creates it
"wb"
for writing bytes, doesn't throw an exception if the file doesn't exist, but creates it
"a"
for appending text, throws an exception if the file doesn't exist
"ab"
for appending bytes, throws an exception if the file doesn't exist
"x"
for creating files without opening, throws an exception if the file already exist
For reading files:
txt = file.read() # get the whole text
line = file.readline() # get a line
lines = file.readlines() # get a list of lines
For writing text:
file.write('txt')
For closing:
file.close()
For more detailed and complete info have a look here