使用python在每次迭代的文本文件中写入换行符

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

标签: python file-io

想要在每次迭代中写入换行符,但它无法解决。我使用函数getUser()和abc.txt中的getFriends()读取随机字符串。并在文本文件new_file.txt中写入,但它在每次迭代的第一行写入

输出:['Larina'] ['Oormi','Palky'] ['Kavia'] ['Chakradhari','Chunni']

我需要这种格式:

['Larina'] ['Oormi','Palky']

['Kavia'] ['Chakradhari','Chunni']

with open("new_file.txt", "wb") as sink:
        for i in range(0,2):
            print>>sink, getUser(),getFriends()
            #print>>sink,("\n")

def getUser():
    with open("abc.txt", "rb") as source:
        lines = [line.rstrip() for line in source]
    random_choice = random.sample(lines, 1)
    source.close()
    return(random_choice);
def getFriends():
    with open("abc.txt", "rb") as source:
        lines = source.read().splitlines()

    random_choice = random.sample(lines, 2)
    source.close()
    return(random_choice);

1 个答案:

答案 0 :(得分:0)

您不必关闭source,因为with声明适合您。

试试这段代码:

with open("new_file.txt", "wb") as sink:
        for i in range(0,2):
            sink.write("%s %s\n" % (str(getUser()), str(getFriends())))

def getUser():
    with open("abc.txt", "rb") as source:
        lines = [line.rstrip() for line in source]
    random_choice = random.sample(lines, 1)
    return(random_choice);

def getFriends():
    with open("abc.txt", "rb") as source:
        lines = source.read().splitlines()
    random_choice = random.sample(lines, 2)
    return(random_choice)