编程新建一个名为test.txt文件,存放在代码文件所在目录中,并且打开该文件。然后写入如图1-1所示内容到文件中。最后分别读取5个字符、读取第一行字符串、读取第三行的字符串,读取所有字符串。如图1-2所示。 图1-1 图1-2 提示:使用文件操作函数open()、write()、read()、readline()、readlines()、seek()、tell()、close()。
时间: 2024-02-09 16:12:41 浏览: 35
好的,这是一个关于文件操作的问题,我可以回答。以下是Python代码实现:
```python
# 新建文件并写入内容
with open('test.txt', 'w') as f:
f.write("Hello, world!\n")
f.write("This is a test file.\n")
f.write("I'm learning file operations.\n")
# 读取文件内容
with open('test.txt', 'r') as f:
# 读取5个字符
print(f.read(5))
# 读取第一行字符串
f.seek(0)
print(f.readline().strip())
# 读取第三行的字符串
f.seek(0)
for i in range(2):
f.readline()
print(f.readline().strip())
# 读取所有字符串
f.seek(0)
print(f.read())
```
运行以上代码,你将看到如下输出:
```
Hello
Hello, world!
I'm learning file operations.
Hello, world!
This is a test file.
I'm learning file operations.
```
其中,第一行输出了读取的前5个字符;第二行输出了第一行字符串;第三行输出了第三行字符串;最后一行输出了所有字符串。