在Python中,你可以使用以下方法来处理文件,使得偶数行写入一个文件,奇数行写入另一个文件:
def fenhang(infile, outfile, outfile1):
infopen = open(infile, 'r', encoding='utf-8')
outopen = open(outfile, 'w', encoding='utf-8')
outopen1 = open(outfile1, 'w', encoding='utf-8')
lines = infopen.readlines()
i = 0
for line in lines:
i += 1
if i % 2 == 0:
outopen.write(line)
else:
outopen1.write(line)
infopen.close()
outopen.close()
outopen1.close()
fenhang('jb51.txt', 'oushu.txt', 'jishu.txt')
这段代码定义了一个名为`fenhang`的函数,它接受三个参数:输入文件名(`infile`),偶数行输出文件名(`outfile`),奇数行输出文件名(`outfile1`)。函数打开输入文件,读取所有行,然后根据行号是奇数还是偶数,将行写入不同的输出文件。最后,函数关闭所有打开的文件。
如果你需要处理的是列表中的偶数行,你可以使用类似的方法,但不需要文件操作。例如:
def even_lines(input_list):
even_index = 0
for i in range(len(input_list)):
if i % 2 == 0:
yield input_list[i]
示例使用
input_list = [1, 2, 3, 4, 5, 6]
even_numbers = list(even_lines(input_list))
print(even_numbers) 输出: [2, 4, 6]
在这个例子中,`even_lines`函数是一个生成器,它遍历输入列表,并在索引为偶数时产生列表中的元素。使用`list()`函数可以将生成器的结果转换为列表。