如何在文本文件中将备用行写入python中的另一个文本文件?

时间:2016-03-22 07:06:02

标签: python

`import fileinput
f = open('file1', 'r')
f1 = open('file2', 'w')
f2 = open('file3', 'w')
i=0
for line in f:`
    if i==0:
        f1.write(line)
        i=1
    else:
        f2.write(line)
        i=0
f1.close()
f2.close()`

尝试使用此代码并没有给我带来任何结果。我的文件也有分布在多行的文本。这会有用吗?

3 个答案:

答案 0 :(得分:0)

你可以尝试,

text = f.readlines()

for line in text:

我假设您的原始代码中没有“'”符号。

答案 1 :(得分:-1)

由于文件对象支持延迟迭代(有效地表现为生成器),我建议使用生成器接口,即next函数。

  

通过调用next()方法从迭代器中检索下一个项目。如果给定default,则在迭代器耗尽时返回,否则引发StopIteration

with open('file1', 'r') as src, open('file2', 'w') as dst_odd, open('file3', 'w') as dst_even:
    odd_line = next(src)
    dst_odd.write(odd_line)
    even_line = next(src)
    dst_even.write(even_line)

您还需要处理EOF - 为此,您可能会遇到StopIteration异常。

with open('file1', 'r') as src, open('file2', 'w') as dst_odd, open('file3', 'w') as dst_even:
    try:
        odd_line = next(src)
    except StopIteration:
        pass  # stop processing - end of file
    dst_odd.write(odd_line)
    try:
        even_line = next(src)
    except StopIteration:
        pass  # stop processing - end of file
    dst_even.write(even_line)

为了进一步减少代码中的重复并概括任意数量的输出文件,您可以使用以下内容:

import itertools
with open('file1', 'r') as src, open('file2', 'w') as dst_odd, open('file3', 'w') as dst_even:
    destinations = itertools.cycle([dst_odd, dst_even])  # additional file object may be passed here.
    try:
        next_line = next(src)
    except StopIteration:
        pass  # stop processing - end of file
    next_dst = next(destinations)
    next_dst.write(next_line)

答案 2 :(得分:-1)

首先,出于安全考虑,您必须使用with关键字打开文件。即使您没有使用实际代码处理更重要的项目,也有良好的编程习惯。

我建议你一个简单的方法来解决你的问题:

  1. 使用readlines()方法读取文件。这将生成一个列表,其中文件的每一行代表此列表的元素。

    with open('file.txt', 'r') as f: lines = f.readlines()

  2. 利用lines列表重新排列为2个单独的列表奇数行和偶数行:

    even_lines, odd_lines = lines[::2], lines[1::2]

  3. 在每个子列表上循环,将其行保存在您选择的文件中:

    with open('file1.txt','w') as f1: for odd_line in odd_lines: f1.write(odd_line)

    with open('file2.txt','w') as f2: for even_line in even_lines: f2.write(even_line)

  4. 完整程序:

    让我们将上面的代码集合到一个小应用程序中:

    # Safely open your file
    with open('file.txt', 'r') as f:
       lines = f.readlines()
    
    # Rearrange the lines according to the logic you are looking for
    even_lines, odd_lines = lines[::2], lines[1::2]
    
    # Safely open your files
    with open('file1.txt','w') as f1:
       for odd_line in odd_lines:
           f1.write(odd_line)
    
    with open('file2.txt','w') as f2:
       for even_line in even_lines:
           f2.write(even_line)
    

    演示:

    secuirty@begueradj:~/Desktop$ python tester.py 
    security@begueradj:~/Desktop$ cat file1.txt
    This is the line number 1
    This is the line number 3
    This is the line number 5
    security@begueradj:~/Desktop$ cat file2.txt
    This is the line number 0
    This is the line number 2
    This is the line number 4
    hacker@begueradj:~/Desktop$