0
import os, sys
inputFilename = 'X.txt'
if not os.path.exists(inputFilename):
    print('The file %s does not exist. Quitting...' % (inputFilename))
    sys.exit()

This code is only meant to run when the txt file X is not found. But for some reason it keeps running these lines, even though the file does exist in the right place. Any ideas what I'm doing wrong? I've tried moving everything into a separate folder and renaming file, nothing seems to be working.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    if the file does not exist this yields a boolean value of `false`. Not of `false` is `true` and thus it runs the code in the `if` statement – AzyCrw4282 Jul 05 '20 at 16:02
  • if os.path.exists(inputFilename) != True: Furthermore you directly link to the Filename, there is no path mentioned, depending on your IDE there might be some problems this way, try using the path to the file as well, like this: if os.path.exists(os.path.join(path_to_file, inputFilename)) != True: – Andreas Jul 05 '20 at 16:03
  • 1
    The code works perfectly fine for me. Where are you running it from in relation to the file? Also can I suggest to use path from pathlib – IKAdmin Jul 05 '20 at 16:04
  • 1
    You are likely confusing the current working directory (which is what a relative path like `X.txt` resolves against) and the directory where your script is saved. – chepner Jul 05 '20 at 16:06
  • Does this answer your question? [File Not Found Error in Python](https://stackoverflow.com/questions/17658856/file-not-found-error-in-python) – wjandrea Jul 05 '20 at 16:08

2 Answers2

0
  1. Where is the text file located?
  2. Where are you running the python code from?

The answers to 1. and 2. should both be the same. If not, there's your issue.

I think you might be able to pass in an absolute path instead of just 'X.txt' to inputFileName. This way the directory layout won't matter.

There doesn't seem to be anything inherently wrong with your code. I tested out it locally and it works.

Uy Tran
  • 11
  • 1
0

Make sure that the IDE you're using recognises the folder, otherwise it might not find the file even if it exists in the folder.

Fx if you're using vs code, click on the option "open folder" and add the folder as a working platform. Check how to for whichever IDE you're using.

On another note, if you're only using files it might be better practice to use isfile() instead of exists()

exists() is for files and directories, whereas isfile() is for just files. For just directories you can use isdir()

ArcticCry
  • 16
  • 2