Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)
recategorized by

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?

1 Answer

0 votes
by (25.1k points)

This issue is occurring because you are using Popen incorrectly. You need pass the command and arguments in a list. Like this:

subprocess.Popen(['powershell.exe', '-Command', ...])

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...