Afsheen Taheri
Afsheen Taheri

Reputation: 139

Python - Having trouble opening a file with spaces

So I am attempting to open multiple files within the "subnet folder" folder. However, it is not allowing me to open a specific file that contains spaces in it

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

This is the error I receive:

FileNotFoundError: [Errno 2] No such file or directory: '10.181.136.0  24.csv'

The file is most definitely there so I'm not sure what the problem is.

Any help is appreciated. Thanks

Upvotes: 1

Views: 8850

Answers (3)

chepner
chepner

Reputation: 531345

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(...)

Upvotes: 4

fuglede
fuglede

Reputation: 18201

The filename ends up being relative to your CWD, so you want to do something like

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

Upvotes: 1

Mason Caiby
Mason Caiby

Reputation: 1924

It looks like you need to add Subnet Folder in front of the file name. You could use os

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

Upvotes: 1

Related Questions