typora/note/Python/文件操作.md
2024-12-12 10:48:55 +08:00

87 lines
1.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

### 读文件
- 读取全部内容
```python
f = open("xxx.py")
f.read()
```
- 读取指定多少个字符内容
```python
f = open("xxx.py")
f.read(2)
```
- 按行读取:如果返回空就代表文件读完了
```python
>>> f = open("xxx.py")
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
```
- 读取所有行到list
```python
>>> f = open("module_support.py")
>>> f.readlines()
['#!/usr/bin/python3\n', '\n', 'def add(a, b):\n', ' return a + b\n', '\n', 'if __name__ == "__main__":\n', ' print("__main__")\n', 'else:\n', ' print(__name__)\n']
>>>
```
- for循环读取每一行
```python
>>> f = open("module_support.py")
>>> for line in f:
... print(line, end = "")
...
#!/usr/bin/python3
def add(a, b):
return a + b
if __name__ == "__main__":
print("__main__")
else:
print(__name__)
>>>
```
### 写文件
```python
f = open("module_support.py", "a") # 追加
f = open("module_support.py", "w") # 文件不存在创建,存在就清空
f.wtite("one line string")
f.close()
```
### 文件操作cursor
- f.tell() 显示当前cursor位置
- f.seek(offset, from_what) 重新设置cursor位置
- from_what 的值, 如果是 0 表示开头, 如果是 1 表示当前位置, 2 表示文件的结尾,例如:
- seek(x, 0) 从起始位置即文件首行首字符开始移动 x 个字符
- seek(x, 1) 表示从当前位置往后移动x个字符
- seek(-x, 2)表示从文件的结尾往前移动x个字符
```python
>>> f = open("module_support.py", "a")
>>> f.tell()
128
>>> f = open("module_support.py", "a")
>>> f.seek(10, 0)
10
>>>
```