Lukas Gooder
Lukas Gooder

Reputation: 1

File not being found because of a space in it

Ok so I'm writing a script that opens files but when there is a space it doesn't recognize that there is more to the path afterwards.

import os
OpenFile = 'C:\\Users\\Me\\file name.txt'
os.system(OpenFile)

This is the code being used but it gives the error (Notice it doesn't include the name.txt after file)

'C:\Users\Me\file' is not recognized as an internal or external command,
operable program or batch file.

Is there any way to fix this?

Upvotes: 0

Views: 8718

Answers (2)

Simon
Simon

Reputation: 421

you just need '"..."' to pass the string ("...") to the shell.

import os
OpenFile = '"C:\\Users\\Me\\file name.txt"'
os.system(OpenFile)

Upvotes: 0

Pratit
Pratit

Reputation: 11

You can use the caret character (^) to escape spaces in file path. Just add it before the space.

import os
OpenFile = 'C:\\Users\\Me\\file^ name.txt'
os.system(OpenFile)

By using this the space in the filename does not disrupt the program from opening the file. This approach is way easier than using subprocess module. Your file should open now using this code.

Upvotes: 1

Related Questions