到目前为止,在python上我使用代码创建了一个文件:
text_file = open("Sentences_Positions.txt", "w")
text_file.write (str(positions))
text_file.write (str(ssplit))
text_file.close()
代码生成文件并将单个单词写入我先前拆分的单词,我需要找到一种方法来打开文件并加入拆分单词然后打印我尝试过。
text_file = open("Sentences_Positions.txt", "r")
rejoin = ("Sentences_positions.txt").join('')
print (rejoin)
但所有这一切都是在shell中打印一个空行,我应该如何处理这个以及我可以尝试其他代码?
答案 0 :(得分:0)
替换:
rejoin = ("Sentences_positions.txt").join('')
使用:
rejoin = ''.join(text_file.read().split(' '))
此外,您可能不应该使用open
,而是使用上下文管理器:
with open("Sentences_Positions.txt") as text_file:
rejoin = ''.join(text_file.read().split(' '))
print (rejoin)
否则文件仍然打开。使用上下文管理器,它将在完成后关闭它。 (对于代码的第一部分也是如此)。
答案 1 :(得分:0)
阅读文件内容并按''
content = textfile.read().split(' ')
print ''.join(content)