Python - Having Trouble Opening a File With Spaces

whitespaces in the path of windows filepath

There is no problem with whitespaces in the path since you're not using the "shell" to open the file. Here is a session from the windows console to prove the point. You're doing something else wrong

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on wi
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> os.makedirs("C:/ABC/SEM 2/testfiles")
>>> open("C:/ABC/SEM 2/testfiles/all.txt","w")
<open file 'C:/ABC/SEM 2/testfiles/all.txt', mode 'w' at 0x0000000001D95420>
>>> exit()

C:\Users\Gnibbler>dir "C:\ABC\SEM 2\testfiles"
Volume in drive C has no label.
Volume Serial Number is 46A0-BB64

Directory of c:\ABC\SEM 2\testfiles

13/02/2013 10:20 PM <DIR> .
13/02/2013 10:20 PM <DIR> ..
13/02/2013 10:20 PM 0 all.txt
1 File(s) 0 bytes
2 Dir(s) 78,929,309,696 bytes free

C:\Users\Gnibbler>

Python - Having trouble opening a file with spaces

Spaces aren't the problem here; relative paths are.

os.listdir yields only the names of the files, not a path relative to your current working directory. If you want to open the file, you need to use the relative path.

d = pathlib.Path.cwd() / "Subnet folder"
for filename in os.listdir(d):
f = open(d / filename, 'r', encoding="ISO-8859-1")

Note that you don't actually need to use cwd here, as both listdir and open already interpret relative paths against your current working directory.

for filename in os.listdir("Subnet folder"):
f = open(os.path.join("Subnet folder", filename), ...)

Or, change your working directory first. Then, the file name itself will be a valid relative path for open.

os.chdir("Subnet folder)
for filename in os.listdir():
f = open(filename, ...)

Finally, you could avoid os.listdir altogether, because if the Path object refers to a directory, you can iterate over its contents directly. This iteration yields a series of Path instances, each of which has an open method that can be used in place of the ordinary open function.

for filename in (pathlib.Path.cwd() / "Subnet Folder").iterdir():
f = filename.open(...)

Python, open.system function - error with having spaces in the file name

You can put the file name in double quotes to preserve whitespaces:

os.system('"%s"' % File)

python open() gives me error while opening files having a space in naming(i.e. example text.txt)

The '\' is only used in the shell to escape the following space. In python, you can just include the whole thing in quotes:
with open('Users/vandit/Desktop/example text.txt', 'w') as f:

Also (if you are on windows) if you still get an error, try prepending the string with the drive in which your Windows is installed, which is mostly C:\. So it will become: with open('C:/Users/vandit/Desktop/example text.txt', 'w') as f:

How do you open a file with a space in its name?

You're having that problem because the script you're trying to execute does not contain the same code as the code you originally posted.

In your text-opener.py you're trying to open a file as follows:

os.system("open filename")

According to your example, filename = "boot strap.css". Thus you're trying to execute the following command:

os.system("open boot strap.css")

which from the terminal would simply translate to a command of the form

open boot strap.css

and indeed, in that case, I also receive your error. What you need to do is wrap filename with quotes, that is

os.system("open '"+ filename + "'")

or simply use the code you originally posted.

In summary

The code you originally posted is not the same code you were trying to execute! You were basically trying to pass different parameters to open.

open file with spaces in path

The solution that worked for me is to delete the start option as described here : Opening file with spaces in Windows via Command Prompt

import subprocess
subprocess.call(['cmd','/c',"C:/Users/akg/Desktop/file 1.png"])

or

subprocess.call(['cmd', '/c', 'start', "", "C:/Users/akg/Desktop/file 1.png"])

Thank you all

How to open a file with Python with white spaces in the name?

I needed to use os.startfile() and also point it to the root directory, which I had stored previously.

os.startfile(new_folder + '\\' + file) works

Problem in running an exe file in command line when there is space in paths of files

Short answer: Use a shorthanded version of the full path: "C:/Progra~1/WinRAR/winrar.exe"


Longer answer: Command prompts don't like space in between paths. Usually within the prompt itself you will need to use quotation marks to signify the full path that contains space, or use a shorthand convention of the ~1 (tilde notation).

Here is a web archived Microsoft knowledge base that I dug up, which I'll include here as a copy in case it goes down:

Windows generates short file names from long file names in the
following manner:

  • Windows deletes any invalid characters and spaces
    from the file name. Invalid characters include: . " / \ [ ] : ; = ,

  • Because short file names can contain only one period (.), Windows
    removes additional periods from the file name if valid, non-space
    characters follow the final period in the file name.

    For example,
    Windows generates the short file name Thisis~1.txt
    from the long file
    name This is a really long filename.123.456.789.txt

    Otherwise, Windows
    ignores the final period and uses the next to the last period. For
    example, Windows generates the short file name Thisis~1.789 from the
    long file name This is a really long filename.123.456.789.

  • Windows
    truncates the file name, if necessary, to six characters and appends a
    tilde (~) and a digit. For example, each unique file name created ends
    with "~1." Duplicate file names end with "~2," "~3," and so on.

  • Windows truncates the file name extension to three characters or less.

  • Windows translates all characters in the file name and extension to
    uppercase.

Note that if a folder or file name contains a space, but
less than eight characters, Windows still creates a short file name.
This behavior may cause problems if you attempt to access such a file
or folder over a network. To work around this situation, substitute a
valid character, such as an underscore (_), for the space. If you do
so, Windows does not create a different short file name

For example, "Afile~1.doc" is generated from "A file.doc" because the
long file name contains a space.

No short file name is generated from "A_file.doc" because the file
name contains less than eight characters and does not contain a space.

The short file name "Alongf~1.txt" is generated from the long file
name "A long filename.txt" because the long file name contains more
than eight characters.


Alternative answer: you can try adding quotes in the cmd that you intend to run:

# using f-strings for Python 3.6+
cmd = f'"{winrar_path}" a -hp {password} -ep1 {rar} {f}'

# or using good ol' format:
cmd = '"{path}" a -hp {pw} -ep1 {file} {fl}'.format(path=winrar_path, pw=password, file=rar, fl=f)


Related Topics



Leave a reply



Submit