请对这些函数分别举例
时间: 2023-11-12 17:06:05 浏览: 19
好的,以下是这些函数的简单例子:
1. open()函数:
```python
# 打开一个文件
file = open('example.txt', 'r')
```
2. close()函数:
```python
# 关闭一个文件
file.close()
```
3. read()函数:
```python
# 读取整个文件内容
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
# 读取指定数量的字符
file = open('example.txt', 'r')
content = file.read(10)
print(content)
file.close()
```
4. write()函数:
```python
# 写入一行字符串
file = open('example.txt', 'w')
file.write('Hello, World!')
file.close()
# 写入一组字符串
file = open('example.txt', 'w')
lines = ['Hello', 'World', '!']
file.writelines(lines)
file.close()
```
5. readline()函数:
```python
# 逐行读取文件内容
file = open('example.txt', 'r')
line = file.readline()
while line:
print(line)
line = file.readline()
file.close()
```
6. writelines()函数:
```python
# 向文件中写入一组字符串
file = open('example.txt', 'w')
lines = ['Hello', 'World', '!']
file.writelines(lines)
file.close()
```
7. seek()函数:
```python
# 移动文件指针到指定位置
file = open('example.txt', 'r')
file.seek(5)
content = file.read()
print(content)
file.close()
```
8. tell()函数:
```python
# 获取文件指针的当前位置
file = open('example.txt', 'r')
file.seek(5)
position = file.tell()
print(position)
file.close()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)