Redtunic
Redtunic

Reputation: 25

Why does my python program run with Powershell but not Bash? Using WSL

I have a simple 3 line python program that I am trying to run. It will run in Powershell but not in Bash. All it does is opens a text file and prints the info out in the terminal.

I am using WSL.

with open('C:/Users/me/Desktop/data.txt') as a:
    content = a.read()
    print(content)

I write "python C:/Users/me/Desktop/program.py" and it runs in the shell when I am using Powershell.

However once I switch the shell to Bash and run "python3 directory/program.py" it says "File "C:/Users/me/Desktop/program.py", line 1, in with open('C:/Users/me/Desktop/data.txt') as a: FileNotFoundError [Errno 2] No such file or directory: 'C:/Users/me/Desktop/data.txt'.

As a note, for some reason I need to type python3 rather than python when using Bash for it to even run my program, but in Powershell python rather than python3 works.

So I am just wondering why in Bash the program is found and runs, but the text file itself it says it cannot find. But Powershell does find and run my program including finding the text file it reads.

Thank you

Upvotes: 1

Views: 140

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117148

C:/Users/me/Desktop/data.txt isn't a valid path in the WSL filesystem afaik. Try /mnt/c/Users/me/Desktop/data.txt - or make it work on both platforms by using os.path.expanduser:

import os
filename=os.path.expanduser('~') + '/Desktop/data.txt'

with open(filename) as a:
    content = a.read()
    print(content)

Upvotes: 1

Related Questions