[Tutor] Variable and a raw string
David L Neil
PyTutor at DancesWithMice.info
Mon Jan 20 16:15:16 EST 2020
On 21/01/20 8:50 AM, Alessandro Caudilho wrote:
> Hello all
>
> my code below:
>
> ============================
> from datetime import datetime
>
> state = 'colorado/us'
>
> with open('/home/user/' + state + '.txt', 'a') as f:
> time = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
> f.write(time)
> f.close()
> ============================
>
> And I get FileNotFoundError: [Errno 2] No such file or directory: "/home/user/colorado/us'.txt"
Did you re-type the code or did you copy-paste it from the editor into
this email msg???
(the mixture of quotation-marks/double-quotes and
apostrophe/single-quote in the err.msg, indicates that the above code is
NOT the original)
1 if the code is being run (by "user") from his/her home-directory (ie
/home/user) then all that may be omitted from the open()
2 if your intent is to separate each US State into its own directory,
then would "...US/Colorado..." make for a better stepwise-refinement?
3 otherwise if the "us" part is merely a label, perhaps to distinguish
from some "colorado" in another country, then please see previous responses.
4 Please review open-append in
https://docs.python.org/3/library/functions.html?highlight=open#open
(see also "absolute" and "relative", per (1) above). What happens if one
opens a file in a directory which does not (yet) exist? How does this
differ from attempting to open a file which does not exist (read) or
does not yet exist (append)? (experiment in the Python REPL)
5 given that the file is being processed in-context (with), the close()
is unnecessary, because it is provided auto-magically as part of the
context-manager
(https://docs.python.org/3/reference/compound_stmts.html#the-with-statement)
--
Regards =dn
More information about the Tutor
mailing list