打开文件路径在python中不起作用

Fwi*_*er1 6 python file

我正在编写一个数据库程序,personica 是我的测试对象(我通常会在文件路径的位置使用一个变量,但出于测试和演示目的,我只有一个字符串。)。在我的计算机上的这个确切位置有一个文本文件(顺便说一下,我在这里更改了我的用户名,因为我是偏执狂。),但它说:

Traceback (most recent call last):
File "C:\Users\Admin\Documents\Project 
Documentation\InteractiveExecutable.py", line 46, in <module>
ReadPerson = open("C:/Users/Admin/Documents/Project 
Documentation/personica.txt", 'r')
IOError: [Errno 2] No such file or directory:
'C:/Users/Admin/Documents/Project Documentation/personica.txt'
Run Code Online (Sandbox Code Playgroud)

这是代码行:

ReadPerson = open("C:/Users/Admin/Documents/Project Documentation/personica.txt", 'r')
Run Code Online (Sandbox Code Playgroud)

我确信它就在那里,当我将该地址复制到 Windows 资源管理器时,它会将我带到文本文件。

有谁知道为什么这不起作用?

Ric*_*ica 8

new-ishpathlib模块(在 Python >= 3.4 中可用)非常适合处理类似路径的对象(Windows 和其他操作系统)。

这是路径 - 一路向下的路径

为简化起见:您可以将任何路径(目录和文件路径对象的处理方式完全相同)构建为一个对象,该对象可以是绝对路径对象或相对路径对象。您可以使用原始字符串来创建复杂的路径(即r'string'),并且pathlib会非常宽容。但是,请注意,有比原始字符串更好的构建路径的方法(请参见下文)。

以下是示例:

from pathlib import Path

Path(r'c:\temp\foo.bar') # absolute path
Path(r'c:/temp/foo.bar') # same absolute path
Path('foo.bar') # different path, RELATIVE to current directory
Path('foo.bar').resolve() # resolve converts to absolute path
Path('foo.bar').exists() # check to see if path exists
Run Code Online (Sandbox Code Playgroud)

请注意,如果您使用的是 Windows,请pathlib原谅您在第二个示例中使用“错误的斜杠”。请参阅最后关于为什么您应该始终使用正斜杠的讨论。

一些有用的路径的简单显示 - 例如当前工作目录和用户主页 - 工作方式如下:

# Current directory (relative):
cwd = Path() # or Path('.')
print(cwd)

# Current directory (absolute):
cwd = Path.cwd()
print(cwd)

# User home directory:
home = Path.home()
print(home)

# Something inside the current directory
file_path = Path('some_file.txt') # relative path; or 
file_path = Path()/'some_file.txt' # also relative path
file_path = Path().resolve()/Path('some_file.txt') # absolute path
print(file_path)
Run Code Online (Sandbox Code Playgroud)

要向下导航文件树,您可以执行以下操作。请注意,第一个对象 ,home是 a Path,其余的只是字符串:

some_person = home/'Documents'/'Project Documentation'/'personica.txt' # or
some_person = home.join('Documents','Project Documentation','personica.txt')
Run Code Online (Sandbox Code Playgroud)

要读取位于路径中的文件,您可以使用它的open方法而不是open函数:

with some_person.open() as f:
    dostuff(f)
Run Code Online (Sandbox Code Playgroud)

但是你也可以直接抓取文本!

contents = some_person.read_text()
content_lines = contents.split('\n')
Run Code Online (Sandbox Code Playgroud)

...并直接写入文本!

data = '\n'.join(content_lines)
some_person.write_text(data) # overwrites existing file
Run Code Online (Sandbox Code Playgroud)

以这种方式检查它是文件还是目录(并存在):

some_person.is_dir()
some_person.is_file()
Run Code Online (Sandbox Code Playgroud)

创建一个新的空文件而不像这样打开它(默默地替换任何现有文件):

some_person.touch()
Run Code Online (Sandbox Code Playgroud)

要仅在文件不存在时制作文件,请使用exist_ok=False:

try:
    some_person.touch(exist_ok=False)
except FileExistsError:
    # file exists
Run Code Online (Sandbox Code Playgroud)

创建一个新目录(在当前目录下Path()),如下所示:

Path().mkdir('new/dir') # get errors if Path()/`new` doesn't exist
Path().mkdir('new/dir', parents=True) # will make Path()/`new` if it doesn't exist
Path().mkdir('new/dir', exist_ok=True) # errors ignored if `dir` already exists
Run Code Online (Sandbox Code Playgroud)

以这种方式获取路径的文件扩展名或文件名:

some_person.suffix # empty string if no extension
some_person.stem # note: works on directories too
Run Code Online (Sandbox Code Playgroud)

使用name该路径的整个最后一部分(茎和扩展,如果他们在那里):

some_person.name # note: works on directories too
Run Code Online (Sandbox Code Playgroud)

使用以下with_name方法重命名文件(返回相同的路径对象,但使用新文件名):

new_person = some_person.with_name('personica_new.txt')
Run Code Online (Sandbox Code Playgroud)

您可以使用以下命令遍历目录中的所有“东西” iterdir:

all_the_things = list(Path().iterdir()) # returns a list of Path objects
Run Code Online (Sandbox Code Playgroud)

侧边栏:反斜杠 ( \)

在路径字符串中使用反斜杠时要小心,尤其是用反斜杠结束路径。与任何字符串一样,即使在原始输入模式下,Python 也会将该终止反斜杠读取为转义字符。观察:

>>> r'\'
  File "<stdin>", line 1
    r'\'
       ^
SyntaxError: EOL while scanning string literal
Run Code Online (Sandbox Code Playgroud)

因此,如果您不知道此问题,这将给出一个非常神秘的错误消息:

>>> Path(r'C:\')
  File "<stdin>", line 1
    Path(r'\')
             ^
SyntaxError: EOL while scanning string literal
Run Code Online (Sandbox Code Playgroud)

此错误的原因\'是假定为字符串中的单引号。这工作正常:('\''第二个单引号结束字符串)。

如果您坚持使用反斜杠,请务必使用原始输入模式,否则您会遇到问题。例如,'\t'字符代表制表符。所以当你这样做时(没有原始输入):

>>> Path('C:\temp')
Run Code Online (Sandbox Code Playgroud)

您正在将制表符放入路径中。这是完全合法的,Python 不会抱怨,直到你做一些导致 Windows 尝试将它变成真正的 Windows 路径的事情:

>>> Path('C:\temp').resolve()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\temp'
Run Code Online (Sandbox Code Playgroud)

如果您不知道发生了什么,这也是一个非常神秘的错误!最好在处理路径时完全避免使用反斜杠字符。

预防问题

当您创建文件并错误地添加了双扩展名时,您的问题就出现了。要使用 防止出现此问题pathlib,请使用以下touch方法制作文件:

some_person = Path.home()/'Documents'/'Project Documentation'/'personica.txt'
some_person.touch()
Run Code Online (Sandbox Code Playgroud)