[英]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
谢谢
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. os.listdir
只产生文件的名称,而不是相对于您当前工作目录的路径。 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.请注意,您实际上不需要在此处使用
cwd
,因为listdir
和open
都已经针对您当前的工作目录解释了相对路径。
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
.然后,文件名本身将是
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.最后,您可以完全避免
os.listdir
,因为如果Path
object 引用一个目录,您可以直接迭代其内容。 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.这个迭代产生了一系列
Path
实例,每个实例都有一个open
方法,可以用来代替普通的open
function。
for filename in (pathlib.Path.cwd() / "Subnet Folder").iterdir():
f = filename.open(...)
It looks like you need to add Subnet Folder
in front of the file name.看起来您需要在文件名前面添加
Subnet Folder
。 You could use os
你可以使用
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")
The filename
ends up being relative to your CWD, so you want to do something like filename
最终与您的 CWD 相关,因此您想做类似的事情
folder = pathlib.Path.cwd() / "Subnet folder"
for filename in os.listdir(folder):
f = open(folder / filename, 'r', encoding="ISO-8859-1")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.