1

I understand that this question may exist, however I am just trying to figure out my formatting. I am not the best when it comes to formatting things like this and am just doing a bit of guess work that just leads to issues.

I have a custom file type that it must save to, a .gcom and a file name that is declared with the function. Currently the function looks like this:

def cComFile(): # This will NOT write command code (Yet) I want to see if file creation works!
    filetype='.gcom'
    commands_Directory = 'C:\\Genisis_AI\\Commands\\' # Unused at the moment
    file_name = command
    if os.path.isfile(("C:\\Genisis_AI\\Commands\\{}").format(file_name).join("{}").format(filetype)):
        a = raw_input(('{} already exists! Would you like to overwrite this? [Y/N]: ').format(cComFile.file_name))
        string.lower(a)
        if a == 'y':
            print(("Command: {} , has been rewritten!").format(file_name))
        elif a == 'n':
            pass
    else:
        f = open((cComFile.commands_Directory.join(cComFile.file_name.join(cComFile.filetype)),'w+'))
        f.write('command was made')
        print(('Command made" {}').format(cComFile.command))

I am getting an issue with line 135 which is the following line:

if os.path.isfile(("C:\\Genisis_AI\\Commands\\{}").format(file_name).join("{}").format(filetype)):

The error I am receiving is the following:

Traceback (most recent call last):
  File "testing/aaa.py", line 149, in <module>
    cComFile('test')
  File "testing/aaa.py", line 135, in cComFile
    if os.path.isfile(("C:\\Genisis_AI\\Commands\\{}").format(file_name).join("{}").format(filetype)):
KeyError: 'C'

I understand that I am most likely doing this all the wrong way but its a learning experience I suppose. And the chances are that me getting that wrong means that the formatting for the rest of this function are also incorrect as well. Thank you for reading and any help would be nice.

(I understand this is messy and I don't mind it at the moment, I tend to clean up after things work)

5
  • 3
    What is the .join("{}") supposed to accomplish? Are you just trying to append "{}" to the end of the string? Because that's not how you do it. Commented May 10, 2018 at 13:18
  • KeyError means that you are calling a dictionnary with a Key that does not exist in this dict. Commented May 10, 2018 at 13:18
  • @jwodder I use {} with formatting and because I dont tend to use this with large strings like what I have to use right now I went and basically stuck what I thought "May" work together, also the reason for the large amount of join and formattings with it. How would this be done for large strings with variables and such?? Sorry this may be unclear, Ill try and rewrite it to make it more clear for you if needed. Commented May 10, 2018 at 13:22
  • As a troubleshooting step, print the result of ("C:\\Genisis_AI\\Commands\\{}").format(file_name).join("{}") and compare that to your expectation. It should become apparent what's happening. Commented May 10, 2018 at 13:25
  • Thak you everyone for the help. Both Answers are correct however I chose Angubelu's response due to the variety of methods given. Commented May 10, 2018 at 13:32

3 Answers 3

2

You can pass several arguments to format:

if os.path.isfile("C:\\Genisis_AI\\Commands\\{}.{}".format(file_name, filetype)):

Or if you're using Python 3.6 (note the f before the string):

if os.path.isfile(f"C:\\Genisis_AI\\Commands\\{file_name}.{filetype}"):

Or if you prefer the % syntax:

if os.path.isfile("C:\\Genisis_AI\\Commands\\%s.%s" % (file_name, filetype)):
Sign up to request clarification or add additional context in comments.

Comments

1

you can pass multiuple values to format function like this, with multiple '{}'.

"C:\\Genisis_AI\\Commands\\{}.{}".format(file_name, filetype)

Comments

0

So basically you jut want to check if a file exists? Why not use a try statement instead of the if?

import errno
try:
  with open(filename,'w') as file:
    # do stuff with the file
except IOError as e:
  # if returned error is [Errno 2] "No such file or directory"
  if e.errno == errno.ENOENT:
    #do something else

This uses the errno module which makes available error codes from your system. This works for me on windows, may be slightly different on Linux not sure.

1 Comment

Ill look into this module. I will most likely use this once everything else for the script is done as this does appear a bit cleaner. However it may not be my initial go to.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.