使用Python操作文本文件中的行

时间:2017-05-31 15:59:06

标签: python

我有一个文本文件,包含一些单词,每个单独的行。如何创建一个新文本文件,将原始文件中的每2或3或X行/单词放在一行中?

例如,这是输入:

one

two

three

four

five

six

seven

eight

输出我想要的东西:

one two

three four

five six

seven eight

3 个答案:

答案 0 :(得分:1)

我写过这篇文章让你开始。它读取第一个文件'input.txt',然后将指定数量的行写入新文件'new.txt'。

lines_to_write = 5 #amount of lines to write from old file to new

with open('input.txt') as f:
    data = f.readlines()

with open('new.txt', 'w') as f:
    for x in range(lines_to_write):
        f.write(data[x])

这显示了如何操作文件,应该是你开始的良好基础。

答案 1 :(得分:0)

您似乎希望将可变数量的行写入一行。所以,我编写了一个列表理解,它将组合可变数量的行。

with open("in.txt","r") as fi, open("out.txt","w") as fo:
    li = fi.readlines()
    inBetween = 2
    fo.write("\n".join(" ".join(line.strip() for line in li[i:i+inBetween]) for i in range(0,len(li),inBetween)))

答案 2 :(得分:0)

每隔一行:

for x in xrange(len(v.splitlines())):
    if x%2 == 0:
        print " ".join(v.splitlines()[x:x+2])

每三行:

for x in xrange(len(v.splitlines())):
    if x%3 == 0:
        print " ".join(v.splitlines()[x:x+3]

更短的:

[ " ".join(v.splitlines()[x:x+2]) for x in xrange(len(v.splitlines())) if x%2 == 0 ]
[ " ".join(v.splitlines()[x:x+3]) for x in xrange(len(v.splitlines())) if x%3 == 0 ]

依旧......