从文件demo.xt中读取内容,将其中的奇数行写入文件 python
时间: 2024-03-04 16:49:24 浏览: 24
好的,这里是Python代码实现从文件demo.txt中读取内容,将其中的奇数行写入文件的方法:
```python
with open('demo.txt', 'r') as f:
lines = f.readlines()
with open('output.txt', 'w') as f:
for i in range(len(lines)):
if i % 2 == 0:
f.write(lines[i])
```
首先,我们使用`with open('demo.txt', 'r') as f`语句打开demo.txt文件,并使用`f.readlines()`方法将文件中的所有内容读取到一个列表中。然后,我们使用`with open('output.txt', 'w') as f`语句打开一个名为output.txt的文件,并以写入模式写入奇数行。
在`for`循环中,我们使用`range(len(lines))`生成一个0到`len(lines)-1`的数字序列,表示文件中每一行的索引。如果当前行的索引是偶数,我们就使用`f.write(lines[i])`语句将该行写入output.txt文件中。
希望能够帮助到你!
相关问题
python将数据写入demo6.txt并读取文本文件每行最后一个字
可以使用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
.
```
从D:\demo.txt文件中一行一行地读取文件。(只读)
你可以使用Python内置的open函数来打开文件并读取内容。以下是一个示例代码,可以实现逐行读取文件的功能:
```python
with open('D:/demo.txt', 'r') as f:
for line in f:
print(line)
```
该代码使用了Python的with语句,在代码块执行完毕后自动关闭文件。open函数的第一个参数是文件的路径,第二个参数是打开文件的模式,'r'表示只读模式。在循环中,我们使用for语句逐行读取文件内容,并将每一行打印出来。