Craig
Craig

Reputation: 3

python3 error when passing variable into os.chdir

I am trying to find a specific pathname and pass this into os.chdir so I can run a command in that directory. I won't know the exact pathname hence why I have to run the find command. I have tried several ways to do this and each comes with a new error. The code below is one of the ways I have tried, can anyone suggest the best way to do this? Or how to fix this error?

Source Code:

import os
import subprocess

os.system('find ~ -path "*MyDir" > MyDir.txt')

output = subprocess.check_output("cat MyDir.txt", shell=True)

os.chdir(output)

os.system("file * > MyDir/File.txt")

The error:

Traceback (most recent call last):
File "sub1.py", line 8, in <module>
os.chdir(output)
FileNotFoundError: [Errno 2] No such file or directory: b'/Users/MyhomeDir/Desktop/MyDir\n'

I know that directory exists and presume it has something to do with the b' and \n'. I just don't know what the problem is.

Upvotes: 0

Views: 625

Answers (1)

DeepSpace
DeepSpace

Reputation: 81654

Get rid of the \n with strip:

output = subprocess.check_output("cat MyDir.txt", shell=True).strip()
os.chdir(output)

Upvotes: 2

Related Questions