Python-基础(3)-files

文件处理

open函数 buildin function

1
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)`

File access modes

1
2
3
4
5
6
7
8
Character	Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)

Read a file

In Python 3, If files do not open in binary mode, the encoding will be determined by
or user's input.
1
2
3
4
5
6
```python
>>> with open("/etc/hosts", encoding="utf-8") as f:
... content = f.read()
...
>>> print(type(content))
<class 'str'>

In python3 binary mode

1
2
3
4
5
>>> with open("/etc/hosts", "rb") as f:
... content = f.read()
...
>>> print(type(content))
<class 'bytes'>

In python2

1
2
3
4
5
6
7
## The content of the file is a byte string, not a Unicode string.
>>> with open("/etc/passwd") as f:
... content = f.read()
>>> print(type(content))
<type 'str'>
>>> print(type(content.decode("utf-8")))
<type 'unicode'>

Write a File

1
2
3
>>> file_content = "Python is great!"
>>> with open("check.txt", "w") as file:
... file.write(file_content)

Copy a file

1
2
3
>>> from distutils.file_util import copy_file
>>> copy_file("a", "b")
('b', 1)

Move a File

1
2
3
>>> from distutils.file_util import move_file
>>> move_file("./a", "./b")
'./b'

Readline

1
2
3
4
5
6
7
8
## If you are not using linux machine try to change the file path to read
>>> 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