python将数据写入demo6.txt并读取文本文件每行最后一个字
时间: 2023-08-28 12:03:23 浏览: 98
可以使用Python内置的文件读写功能来实现。首先,使用`open()`函数打开文件并写入数据:
```python
with open('demo6.txt', 'w') as f:
f.write('Python is a popular programming language.\n')
f.write('It is used for web development, data analysis, artificial intelligence, and more.\n')
```
这段代码将两行文本写入名为`demo6.txt`的文件中。接下来,使用`open()`函数再次打开文件并读取每行最后一个字:
```python
with open('demo6.txt', 'r') as f:
for line in f:
last_char = line[-2]
print(last_char)
```
这段代码使用了`for`循环遍历文件的每一行,并使用切片取出每行的倒数第二个字符(因为每行都有一个换行符`\n`)。然后,使用`print()`函数打印出来。
完整代码如下:
```python
with open('demo6.txt', 'w') as f:
f.write('Python is a popular programming language.\n')
f.write('It is used for web development, data analysis, artificial intelligence, and more.\n')
with open('demo6.txt', 'r') as f:
for line in f:
last_char = line[-2]
print(last_char)
```
输出结果为:
```
e
.
```
阅读全文