Table of Contents
在Python2中,从文件系统中读取文件的内容,不会被解码。 也就是说,文件的内容是字节字符串,而不是Unicode字符串。
>>> with open("/etc/passwd") as f:
... content = f.read()
>>> print(type(content))
<type 'str'>
>>> print(type(content.decode("utf-8")))
<type 'unicode'>
在Python3中,open
提供了一个 encoding
选项。如果文件不是有二进制模式打开的话,
编码将由 locale.getpreferredencoding(False)
或者用户输入决定。
>>> with open("/etc/hosts", encoding="utf-8") as f:
... content = f.read()
...
>>> print(type(content))
<class 'str'>
二进制模式
>>> with open("/etc/hosts", "rb") as f:
... content = f.read()
...
>>> print(type(content))
<class 'bytes'>
>>> with open("/etc/hosts") as f:
... for line in f:
... print(line, end='')
...
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
>>> chunk_size = 16
>>> content = ''
>>> with open('/etc/hosts') as f:
... for c in iter(lambda: f.read(chunk_size), ''):
... content += c
...
>>> print(content)
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
>>> content = "Awesome Python!"
>>> with open("foo.txt", "w") as f:
... f.write(content)
>>> import os
>>> os.symlink("foo", "bar")
>>> os.readlink("bar")
'foo'
>>> from distutils.file_util import copy_file
>>> copy_file("foo", "bar")
('bar', 1)
>>> from distutils.file_util import move_file
>>> move_file("./foo", "./bar")
'./bar'
>>> >>> import os
>>> dirs = os.listdir(".")
在Python3.6之后,我们可以使用 os.scandir
去列出目录。它是更加方便,因为 os.scandir
返回一个 os.DirEntry
对象的迭代器。
在这个情况下,我们可以通过访问 os.DirEntry
的属性,获取文件信息。
更多信息请看 document.
>>> with os.scandir("foo") as it:
... for entry in it:
... st = entry.stat()
...
类似于 mkdir -p /path/to/dest
>>> from distutils.dir_util import mkpath
>>> mkpath("foo/bar/baz")
['foo', 'foo/bar', 'foo/bar/baz']
>>> from distutils.dir_util import copy_tree
>>> copy_tree("foo", "bar")
['bar/baz']
>>> from distutils.dir_util import remove_tree
>>> remove_tree("dir")
>>> from pathlib import Path
>>> p = Path("/Users")
>>> p = p / "Guido" / "pysheeet"
>>> p
PosixPath('/Users/Guido/pysheeet')
>>> from pathlib import Path
>>> p = Path("README.rst")
PosixPath('/Users/Guido/pysheeet/README.rst')
>>> from pathlib import Path
>>> Path.home()
PosixPath('/Users/Guido')
>>> from pathlib import Path
>>> p = Path("README.rst")
>>> p.cwd()
PosixPath('/Users/Guido/pysheeet')
>>> from pathlib import Path
>>> p = Path("README.rst").absolute()
>>> p.root
'/'
>>> p.anchor
'/'
>>> p.parent
PosixPath('/Users/Guido/pysheeet')
>>> p.parent.parent
PosixPath('/Users/Guido')
>>> p.name
'README.rst'
>>> p.suffix
'.rst'
>>> p.stem
'README'
>>> p.as_uri()
'file:///Users/Guido/pysheeet/README.rst'