Reputation: 453
I'm trying to write all the settings from each run of a program to a config file.
This line is giving me strange issues:
cfgfile = open(config_filename, 'w+')
I am getting I/O Errors of the 'No such file or directory' kind. This happens no matter if the flag is w+, a, etc.
I am creating the config_filename from a string stored in a dictionary, concatenated with another short string:
config_filename = my_dict['key'] + '_PARAMETERS.txt'
This is what seems to be causing the problems. I have tested with using
config_filename = 'test' + '_PARAMETERS.txt'
and it works fine, creating the file before writing to it.
Can anyone explain why this happens, I have checked I'm in the same directory and type(config_filename) throws back string as expected. Is this something to do with how dicts store data?
Thanks.
Upvotes: 0
Views: 54
Reputation: 49330
Based on your comment, it looks like you're trying to create a file with a name that includes slashes. This will fail because slashes are not allowed in file names, as they are reserved by the OS to indicate the directory structure. Colons are also not allowed in Windows file names.
Try replacing my_dict['key']
with my_dict['key'].replace('/', '')
, which will remove the slashes and produce a filename like Results_150715_18:32:09_PARAMETERS.txt
. For Windows, add .replace(':','')
to remove the colon as well.
I should clarify that slashes are not allowed in file names, but they are allowed in file paths. The filename you were trying to use would have attempted to create a file named 15_18:32:09_PARAMETERS.txt
in the 07
folder, contained in the Results_15
folder. That isn't what you wanted, but it wouldn't have failed as long as the directory structure existed (on Windows, anyway). Additionally, Windows systems don't allow colons anywhere in the path except to indicate the drive, e.g. C:
.
Upvotes: 1