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' ...

19th Mar 2021, 12:45 PM
sonofpeter.exe
sonofpeter.exe - avatar
4 Answers
+ 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]
19th Mar 2021, 12:54 PM
XXX
XXX - avatar
+ 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)
19th Mar 2021, 12:53 PM
visph
visph - avatar
+ 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
19th Mar 2021, 1:11 PM
visph
visph - avatar
0
visph , XXX thanks . got it . so you're saying i can get away with it if the program ends soon after and/or if i don't use the file again? coz i was really tryna avoid multiple lines .. 😬😅 though since this would be a looping program i guess there's no escaping that ("._.) well thanks again 🙂
19th Mar 2021, 1:07 PM
sonofpeter.exe
sonofpeter.exe - avatar