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

在每次迭代中使用python在文本文件中写入换行符,python,file-io,Python,File Io,希望在每次迭代中使用换行符,但它不起作用。我使用函数getUser()和getFriends()从abc.txt读取随机字符串。并写入文本文件new_file.txt,但每次迭代都会写入第一行 输出:['Larina']['Oormi','Palky']['Kavia']['Chakradhari','Chunni'] with open("new_file.txt", "wb") as sink: for i in range(0,2): print&g

希望在每次迭代中使用换行符,但它不起作用。我使用函数getUser()和getFriends()从abc.txt读取随机字符串。并写入文本文件new_file.txt,但每次迭代都会写入第一行

输出:['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);
我需要以下格式:

[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);

您不必关闭
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)

您不必关闭
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)

无法复制。
print
语句会按原样添加换行符。可能您使用的是一个错误的文本编辑器,它无法将
\n
识别为换行符,并且期望
\r\n
无法复制。
print
语句会按原样添加换行符。可能您使用的是一个不好的文本编辑器,它无法将
\n
识别为换行符,并且需要
\r\n