5
5
----------
6
6
问题
7
7
----------
8
- Your package includes a datafile that your code needs to read. You need to do this in the
9
- most portable way possible.
8
+ 你的包中包含代码需要去读取的数据文件。你需要尽可能地用最便捷的方式来做这件事。
10
9
11
10
|
12
11
13
12
----------
14
13
解决方案
15
14
----------
16
- Suppose you have a package with files organized as follows:
15
+ 假设你的包中的文件组织成如下:
17
16
18
17
.. code-block :: python
19
18
@@ -22,45 +21,33 @@ Suppose you have a package with files organized as follows:
22
21
somedata.dat
23
22
spam.py
24
23
25
- Now suppose the file spam.py wants to read the contents of the file somedata.dat. To do
26
- it, use the following code:
24
+ 现在假设spam.py文件需要读取somedata.dat文件中的内容。你可以用以下代码来完成:
27
25
28
26
.. code-block :: python
29
27
30
28
# spam.py
31
29
import pkgutil
32
30
data = pkgutil.get_data(__package__ , ' somedata.dat' )
33
31
34
- The resulting variable data will be a byte string containing the raw contents of the file.
32
+ 由此产生的变量是包含该文件的原始内容的字节字符串。
35
33
36
34
|
37
35
38
36
----------
39
37
讨论
40
38
----------
41
- To read a datafile, you might be inclined to write code that uses built-in I/O functions,
42
- such as open(). However, there are several problems with this approach.
39
+ 要读取数据文件,你可能会倾向于编写使用内置的I/ O功能的代码,如open()。但是这种方法也有一些问题。
43
40
44
41
45
- First, a package has very little control over the current working directory of the interpreter.
46
- Thus, any I/O operations would have to be programmed to use absolute filenames.
47
- Since each module includes a __file__ variable with the full path, it’s not impossible
48
- to figure out the location, but it’s messy.
42
+ 首先,一个包对解释器的当前工作目录几乎没有控制权。因此,编程时任何I/O操作都必须使用绝对文件名。由于每个模块包含有完整路径的__file__变量,这弄清楚它的路径不是不可能,但它很凌乱。
49
43
50
44
51
- Second, packages are often installed as .zip or .egg files, which don’t preserve the files in
52
- the same way as a normal directory on the filesystem. Thus, if you tried to use open()
53
- on a datafile contained in an archive, it wouldn’t work at all.
45
+ 第二,包通常安装作为.zip或.egg文件,这些文件像文件系统上的一个普通目录一样不会被保留。因此,你试图用open()对一个包含数据文件的归档文件进行操作,它根本不会工作。
54
46
55
47
56
- The pkgutil.get_data() function is meant to be a high-level tool for getting a datafile
57
- regardless of where or how a package has been installed. It will simply “work” and return
58
- the file contents back to you as a byte string.
48
+ pkgutil.get_data()函数是一个读取数据文件的高级工具,不用管包是如何安装以及安装在哪。它只是工作并将文件内容以字节字符串返回给你
59
49
60
50
61
- The first argument to get_data() is a string containing the package name. You can
62
- either supply it directly or use a special variable, such as __package__. The second
63
- argument is the relative name of the file within the package. If necessary, you can navigate
64
- into different directories using standard Unix filename conventions as long as the
65
- final directory is still located within the package.
51
+ get_data()的第一个参数是包含包名的字符串。你可以直接使用包名,也可以使用特殊的变量,比如__package__。第二个参数是包内文件的相对名称。如果有必要,可以使用标准的Unix命名规范到不同的目录,只有最后的目录仍然位于包中。
52
+
66
53
0 commit comments