-2

I need help with the following code:

def CreateFile(shortcut, name):
 try:
    shortcut = open(name, 'x')
 except FileExistsError:
    print('That file already exists. Open it with OpenFile(shortcut, name).')
 else:
    print('File created. Open the file using OpenFile(shortcut, name).')

When I execute it, I get the following error:

IndentationError: unindent does not match any outer indentation level

This error code is pointing out the semicolon after [except FileExistsError:]

Can I please get a solution? This is how I saw other people's code and would like advice. I am creating my own operating system, in which OpenFile(shortcut, name) exists.

  • I'm sorry if this comes off as mean, but can you see the space next to the "try"? – cs95 Dec 12 '18 at 16:52
  • 1
    Python is a strongly typed language and indentation is one of the most basic and key thing you need to pay attention to. Make sure for each block of code the indentation level is consistent (i.e. if you use tab, tab the same amount of time for the same levels, likewise with spaces). – r.ook Dec 12 '18 at 16:54
  • 1
    probably mixed spaced and tabs, fix: https://stackoverflow.com/a/29636895/797495 – Pedro Lobito Dec 12 '18 at 16:56
  • @coldspeed What space? That is the indent after the definition of CreateFile(). – Dakota Plemmons Dec 12 '18 at 17:05
  • Unfortunately copy&pasting code into SO often breaks indentation. Can you confirm with 100% certainty that you indented your code using ASCII space characters (i.e. ASCII code 32) and not tab characters (ASCII code 9)? – Bakuriu Dec 12 '18 at 17:14
  • I am so sorry folks. This question has been self-solved. Apparently Ipython works differently than normal python. To test this, I ran this same piece of code into a normal python3.7 console and it worked with no flaw, and the error code appeared as expected. – Dakota Plemmons Dec 12 '18 at 17:16
  • To add to that, IPython probably doesn't like the try/except blocks. – Dakota Plemmons Dec 12 '18 at 17:19
  • When you get to a resolution, please remember to up-vote useful things and accept your favourite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question. – Prune Dec 12 '18 at 17:20

1 Answers1

0

I faced this error a while back. It happened because the code was copied and pasted directly from a pdf. What I'm suggesting is to basically re-write the code which might solve the problem or another thing that seems to be the problem is the function indentation is smaller than the indentation used for try and except, use a similar indent in both places.

Hope this helps in the progress!

Sumukha Pk
  • 124
  • 1
  • 7