测试常用的文件操作: (1)以读写、只读、只写、追加等多种模式完成文件打开和关闭操作。 (2)用read0、readline(、readlines(方法完成文件数据的读取。 (3)用write(、writelines()方法完成向文件写入数据。
时间: 2023-12-18 22:05:15 浏览: 41
好的,我来给你演示一下常用的文件操作。
1. 文件的打开和关闭:
```python
# 以读写模式打开文件
file = open('example.txt', 'w+')
# 以只读模式打开文件
file = open('example.txt', 'r')
# 以只写模式打开文件
file = open('example.txt', 'w')
# 以追加模式打开文件
file = open('example.txt', 'a')
# 关闭文件
file.close()
```
2. 文件数据的读取:
```python
# 读取整个文件
file = open('example.txt', 'r')
data = file.read()
print(data)
file.close()
# 逐行读取文件
file = open('example.txt', 'r')
for line in file:
print(line)
file.close()
# 读取所有行并以列表形式返回
file = open('example.txt', 'r')
data = file.readlines()
print(data)
file.close()
```
3. 文件数据的写入:
```python
# 写入单行数据
file = open('example.txt', 'w')
file.write('Hello, World!')
file.close()
# 写入多行数据
data = ['First line\n', 'Second line\n', 'Third line\n']
file = open('example.txt', 'w')
file.writelines(data)
file.close()
```
以上就是文件操作的基本示例,你可以根据需要进行修改和调整。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)