我正在尝试制作一个“文本转换器”。例如,我在文件中有不同的单词:
OutputValues
我想将其还原为:
hello:world
learning:python
is:funny
我可以编写脚本以反转单词,但是如果文件中有多行内容。示例:
world:hello
python:learning
funny:is
该脚本将删除所有其他行,仅保留第一行hello:world。我尝试使用hello:world
learning:python
函数和readlines()
函数,但无法正常工作。
我想反转文件可以包含的所有行。 =)
代码如下:
\n
答案 0 :(得分:3)
第with open("combos.txt", "w")
行将覆盖当前文件内容。
您需要
with open("combos.txt", "r") as infile:
data = infile.read()
# create a list of lines, removing the \n in the processs
data = data.split("\n")
# this will delete the original file and create it new
with open("combos.txt", "w") as f:
for line in data:
words = line.split(":")[::-1]
final = ":".join(words)
# write it and add a \n
f.write(final+"\n")