简体   繁体   English

Python - 打开带有空格的文件时遇到问题

[英]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 ,因为listdiropen都已经针对您当前的工作目录解释了相对路径。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM