想要在每次迭代中写入换行符,但它无法解决。我使用函数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);
答案 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)