python用文本编辑器生成一个txt格式的文件,文件内容自定。请写出下列操作的代 码。。 (1)分别用文本文件和二进制文件方式读入,并打印输出文件内容。. (2)分别用绝对路径和相对路径方式读入,并打印输出文件内容。.
时间: 2024-03-22 12:42:11 浏览: 111
以下是一个示例代码,可以实现您的要求:
```python
# 创建一个名为example.txt的文件,并向其中写入一些文本
with open('example.txt', 'w') as file:
file.write('Hello, World!\n')
file.write('This is an example text file.\n')
file.write('It was created using Python.\n')
# 使用文本文件方式读取文件内容并打印输出
with open('example.txt', 'r') as file:
text = file.read()
print(text)
# 使用二进制文件方式读取文件内容并打印输出
with open('example.txt', 'rb') as file:
text = file.read()
print(text)
# 使用绝对路径方式读取文件内容并打印输出
with open('/Users/username/example.txt', 'r') as file:
text = file.read()
print(text)
# 使用相对路径方式读取文件内容并打印输出
with open('example.txt', 'r') as file:
text = file.read()
print(text)
```
需要注意的是,绝对路径和相对路径的具体写法可能因操作系统和文件存储位置而有所不同。在使用时需要根据实际情况进行调整。
阅读全文