1、用文本编辑器生成一个txt格式的文件,文件内容自定。请写出下列操作的代码。 (1)分别用文本文件和二进制文件方式读入,并打印输出文件内容。。(2)分别用绝对路径和相对路径方式读入,并打印输出文件内容。。
时间: 2024-03-22 19:41:53 浏览: 26
好的,以下是代码实现:
1. 生成文件
```python
# 生成文件
with open('example.txt', 'w') as f:
f.write('Hello, world!\n')
f.write('This is an example file.\n')
```
2. 用文本文件方式读入,并打印输出文件内容
```python
# 用文本文件方式读入,并打印输出文件内容
with open('example.txt', 'r') as f:
content = f.read()
print(content)
```
输出结果:
```
Hello, world!
This is an example file.
```
3. 用二进制文件方式读入,并打印输出文件内容
```python
# 用二进制文件方式读入,并打印输出文件内容
with open('example.txt', 'rb') as f:
content = f.read()
print(content)
```
输出结果:
```
b'Hello, world!\nThis is an example file.\n'
```
4. 用绝对路径方式读入,并打印输出文件内容
```python
# 用绝对路径方式读入,并打印输出文件内容
import os
abs_path = os.path.abspath('example.txt')
with open(abs_path, 'r') as f:
content = f.read()
print(content)
```
输出结果同上。
5. 用相对路径方式读入,并打印输出文件内容
```python
# 用相对路径方式读入,并打印输出文件内容
with open('example.txt', 'r') as f:
content = f.read()
print(content)
```
输出结果同上。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)