-1

I hope I have explained this makes sense...

Basically I want to run a python file which will edit itself and delete itself (don't ask) but to delete itself I need the python file to locate its file path (I know I could manually put the file path in but that means the file would have to stay in the same folder). Does anyone know any code I could use so that the program can copy its file path?

Below is the code I am using so that the program can delete itself as you can see I need the file path but I do not know how to copy it within the program.

import os
os.remove(r"filepath")
martineau
  • 99,260
  • 22
  • 139
  • 249
  • Does this answer your question? [How do you properly determine the current script directory in Python?](https://stackoverflow.com/questions/3718657/how-do-you-properly-determine-the-current-script-directory-in-python) – Matthew Strawbridge Nov 18 '20 at 22:37
  • `sys.argv[0]` gives you the name of the script; join that with the current working directory. – Samwise Nov 18 '20 at 22:37

1 Answers1

2

Use __file__.

Test 1:

cat > /tmp/foo.py << EOF
print(__file__)
EOF

python /tmp/foo.py
# output: /tmp/foo.py

Test 2:

cat > /tmp/foo.py << EOF
import os

print(f'deleting self ({__file__})')
os.unlink(__file__)
print('Done.')
EOF

python /tmp/foo.py
# output:
deleting self (/tmp/foo.py)
Done.

# second try
python /tmp/foo.py
# python: can't open file '/tmp/foo.py': [Errno 2] No such file or directory
Pierre D
  • 13,780
  • 6
  • 42
  • 72