打开文件路径在python中不起作用 [英] Opening file path not working in python

查看:287
本文介绍了打开文件路径在python中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个数据库程序,personica是我的测试主题(我通常在文件路径的位置有一个变量,但是出于测试和演示的目的,我只有一个字符串.)我的计算机上的这个确切位置上有一个文本文件(由于我偏执,所以我在这里更改了用户名.),但是它说:

I am writing a database program and personica is my test subject (I would usually have a variable in the place of the file path, but for test and demo purposes I just have a string.). There is a text file at this exact location on my computer (I have changed my username on here, by the way because I am paranoid.), but it says:

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'

这是代码行:

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

我确信它在那里,当我将该地址复制到Windows资源管理器中时,它将带我直接进入文本文件.

I am certain that it is there and when I copy that address into Windows Explorer, it takes me right to the text file.

有人知道为什么这行不通吗?

Anyone know why this is not working?

推荐答案

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

The new-ish pathlib module (available in Python >= 3.4) is great for working with path-like objects (both Windows and for other OSes).

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

To simplify: you can build up any path (directory and file path objects are treated exactly the same) as an object, which can be an absolute path object or a relative path object. You can use raw strings to make complex paths (i.e., r'string') and pathlib will be very forgiving. However, note that there are better ways to build up paths than raw strings (see further down).

以下是示例:

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

请注意,如果您使用的是Windows,则在第二个示例中,pathlib宽恕您使用错误斜杠".请参阅最后的讨论,了解为什么您可能应该始终使用正斜杠.

Note that if you're on Windows pathlib forgives you for using the "wrong slash" in the second example. See discussion at the end about why you should probably always use the forward slash.

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

Simple displaying of some useful paths- such as the current working directory and the user home- works like this:

# 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)

要浏览文件树,您可以执行以下操作.请注意,第一个对象homePath,其余的只是字符串:

To navigate down the file tree, you can do things like this. Note that the first object, home, is a Path and the rest are just strings:

some_person = home/'Documents'/'Project Documentation'/'personica.txt' # or
some_person = home.join('Documents','Project Documentation','personica.txt')

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

To read a file located at a path, you can use its open method rather than the open function:

with some_person.open() as f:
    dostuff(f)

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

But you can also just grab the text directly!

contents = some_person.read_text()
content_lines = contents.split('\n')

...然后直接写文本!

...and WRITE text directly!

data = '\n'.join(content_lines)
some_person.write_text(data) # overwrites existing file

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

Check to see if it is a file or a directory (and exists) this way:

some_person.is_dir()
some_person.is_file()

制作一个新的空文件,而不用这样打开它(静默替换任何现有文件):

Make a new, empty file without opening it like this (silently replaces any existing file):

some_person.touch()

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

try:
    some_person.touch(exist_ok=False)
except FileExistsError:
    # file exists

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

Make a new directory (under the current directory, Path()) like this:

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

通过以下方式获取路径的文件扩展名或文件名:

Get the file extension or filename of a path this way:

some_person.suffix # empty string if no extension
some_person.stem # note: works on directories too

在路径的整个最后部分使用name(如果有,则使用茎和扩展名):

Use name for the entire last part of the path (stem and extension if they are there):

some_person.name # note: works on directories too

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

Rename a file using the with_name method (which returns the same path object but with a new filename):

new_person = some_person.with_name('personica_new.txt')

您可以使用iterdir遍历目录中的所有内容":

You can iterate through all the "stuff' in a directory like so using iterdir:

all_the_things = list(Path().iterdir()) # returns a list of Path objects

侧边栏:反斜杠(\)

在路径字符串中使用反斜杠时要特别小心,尤其要结束带有反斜杠的路径.与 any 字符串一样,即使在原始输入模式下,Python也会将终止反斜杠读取为转义字符.观察:

Sidebar: backslashes (\)

Be careful when using backslashes in a path string, especially ending a path with a backslash. As with any string, Python will read that terminating backslash as an escape character even in raw input mode. Observe:

>>> r'\'
  File "<stdin>", line 1
    r'\'
       ^
SyntaxError: EOL while scanning string literal

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

So this will give a pretty cryptic error message if you are not aware of this issue:

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

此错误的原因是,假定\'是字符串中的单引号 .可以正常工作:'\''(第二个单引号将字符串结尾).

The reason for this error is that \' is assumed to be a single quotation in the string. This works fine: '\'' (the second single quotation ends the string).

如果您坚持使用反斜杠,请确保使用原始输入模式,否则会遇到问题.例如,'\t'字符代表一个制表符.因此,当您执行此操作时(没有原始输入):

If you insist on using backslashes, be sure to use raw input mode or you will run into problems. For example, the '\t' character represents a tab. So when you do this (without raw input):

>>> Path('C:\temp')

您正在将制表符添加到路径中.这是完全合法的,并且Python不会抱怨,直到您执行导致Windows尝试将其转换为真实Windows路径的操作:

You are putting a tab character into your path. This is perfectly legal and Python won't complain until you do something that causes Windows to try turning it into a real Windows path:

>>> 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'

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

This is also a very cryptic error if you do not know what is going on! Best to avoid the backslash characters altogether when messing about with paths.

您的问题是在您创建文件并错误地添加双扩展名时发生的.为防止使用pathlib出现此问题,请使用touch方法制作文件:

Your problem occurred when you created your file and erroneously added a double extension. To prevent this issue using pathlib, use the touch method to make the file:

some_person = Path.home()/'Documents'/'Project Documentation'/'personica.txt'
some_person.touch()

这篇关于打开文件路径在python中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆