0
File Open And Close In Python [SOLVED]
Hey there. I'm revisiting a hangman project and would like to know if this sequence needs to be closed after initialisation, and if is so, how? ::::::CODE:::::: from random import sample word = sample(open('wordbank.txt').read().split('\n'), 1)[0] PS. "word.close()" raises an AttributeError: 'str' ...
4 Antworten
+ 2
Yes, closing a file is always recommended, though in small scripts (especially on SoloLearn where your files are not used by anything else), it isn't much of a problem
The error is there because at the end of the statement, `word` holds a string (because sample(str, 1) returns a str and str[0] also returns a str). Calling word.close() will be the same as calling .close() on a str, and as the str type has no method close(), there will be an error.
Instead, first open the file, then use it in the statement and then close the file
f = open('wordbank.txt')
word = sample(f.read().split('\n'), 1)[0]
f.close()
Or, use a 'with' statement
with open('wordbank.txt') as f:
word = sample(f.read().split('\n'), 1)[0]
+ 3
you get error because word hold the result of sample() call, not the file descriptor used as argument ^^
you must either do:
with open('wordbank.txt') as file:
word = sample(file.read().split('\n'),1)[0]
... where you don't need to explicitly close the file as it is implicitly closed when exiting from 'with' block... or:
file = open('wordbank.txt')
word = sample(file.read().split('\n'),1)[0]
file.close()
... where you should close the file explicitly.
however, files are implicitly closed when script ends, but it's better practice to close all opened files as soon as you don't have to use them anymore (or reopen later in same script, if access are too much time separated)
+ 2
well, it's better practice to close files, than expecting files are closed at script end... all the more if the script is short.
however, if you open file inside a loop, you must close it inside the loop also ^^
anyway, to spare typing, you should use 'with' ;P