1

I'm trying to remove a file in Python 3 on Linux (RHEL) the following way:

os.remove(or.getcwd() + '/file.txt')

(sorry not allowed to publish the real paths).

and it gives me the usual error

No such file or directory: '/path/to/file/file.txt'

(I've respected slash or antislash in the path)

What is strange is that when I just ls the file (by copy pasting, so the very same path) the file does exist.

I've read this post but i'm not on Windows and slash direction seems correct.

Any idea ?

EDIT: as suggested by @DominicPrice os.system('ls') is showing the file while os.listdir() does not show it (but shows other files in the same directory)

EDIT 2: So my issue was due a a bad usage of os.popen. I used this method to copy file but did not wait for the subprocess to be terminated. So my understanding is that the file was not copied yet when I tried to delete it.

Guillaume Petitjean
  • 2,408
  • 1
  • 21
  • 47

2 Answers2

1

The problem is that, as you have explained in the comments, you are creating the file using os.popen("cp ..."). This works asynchronously, so it may not have had time to complete by the time you call os.remove(). You can force python to wait for it to finish by calling the close method:

proc = os.popen("cp myfile myotherfile")
proc.close() # wait for process to finish
os.remove("myotherfile") # we're all good

I would highly recommend staying away from using os.popen in favour of the subprocess library, which has a run function which is way safer to use.

For the specific functions of copying a file, an even better (and cross platform) solution is to use the shutil library:

import shutil
shutil.copyfile("myfile", "myotherfile")
Dominic Price
  • 1,111
  • 8
  • 19
-2

you should use os.path.dirname(__file__). this is an inbuilt function of os module in python. you can read more here. https://www.geeksforgeeks.org/find-path-to-the-given-file-using-python/

Vasu saini
  • 21
  • 6
  • This may or may not be what OP wants. This will return the containing folder for the script, which may be different from the current working directory. Point being, you're answering a different question than the one in the original post, so you may want to clarify that for completeness. This seems more like it should've been a comment, though. – frippe Nov 26 '21 at 09:27
  • don't understand how it solves anything. I know the path of the file, it is the current directory – Guillaume Petitjean Nov 26 '21 at 09:39