Search code examples
pythonpopenpython-3.7

Python FileNotFoundError: [Errno 2] despite giving full filepath


So I have written a piece of code which first runs a powershell command to generate a UTF-8 version of a DAT file (have been having special character issues with the original file, hence the step). Following which I try to open the newly created file. But the issue is, I keep getting 'FileNotFoundError: [Errno 2]' Initially I was only trying with the file name since the newly created file was in the same folder, but then i tried to generate the absolute path as well.

import os
import subprocess

subprocess.Popen('powershell.exe -Command "Get-Content .\Own.DAT | Set-Content -Encoding utf8 Own1.dat"')

filepath = __file__
filepath = filepath[:-7]
with open(filepath+"Own1.dat", "r") as f:

I can confirm that filepath+"Own1.dat" is fetching the correct filepath. Yet can't figure out what the issue could be. Edit: Someone asked for confirmation, here is the message i am getting:

C:\Users\Debojit\MiniConda3\python.exe "E:/My Documents/Work/essbase/ownership/test.py"
Traceback (most recent call last):
  File "E:/My Documents/Work/essbase/ownership/test.py", line 18, in <module>
    with open(filepath+"Own1.dat", "r") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'E:/My Documents/Work/essbase/ownership/Own1.dat'

Process finished with exit code 1

Note: Curiously enough if i put the powershell command into a separate batch file, write a code in the python script to run it, the works without any issues. Here is the code i am talking about:

import os
import subprocess


from subprocess import Popen
p = Popen("conversion.bat", cwd=r"E:\My Documents\Work\essbase\ownership")
stdout, stderr = p.communicate()

filepath = __file__
filepath = filepath[:-7]
with open(filepath+"Own1.dat", "r") as f:

The conversion.bat file contains the following

powershell.exe -Command "Get-Content .\Own.DAT | Set-Content -Encoding utf8 Own1.DAT"

But I don't want to include a separate batch file to go with the python script.

Any idea what might be causing the issue?


Solution

  • I still couldn't figure out why the error was happening. But I found a workaround

    with open("conversion.bat","w") as f:
        f.writelines("powershell.exe -Command \"Get-Content '" +fileName+ "' | Set-Content -Encoding utf8 Own1.dat\"")
    
    
    from subprocess import Popen
    p = Popen("conversion.bat", cwd=os.path.dirname(os.path.realpath(__file__)))
    stdout, stderr = p.communicate()
    
    os.remove("conversion.bat") 
    

    Basically I would create the batch file, run it and then delete it once the file has been created. Don't why I have to use this route, but it works.