在文件中逐行编辑-Python

时间:2020-10-25 12:33:29

标签: python python-3.x

我正在尝试制作一个“文本转换器”。例如,我在文件中有不同的单词:

OutputValues

我想将其还原为:

hello:world
learning:python
is:funny

我可以编写脚本以反转单词,但是如果文件中有多行内容。示例:

world:hello
python:learning
funny:is

该脚本将删除所有其他行,仅保留第一行hello:world。我尝试使用hello:world learning:python 函数和readlines()函数,但无法正常工作。

我想反转文件可以包含的所有行。 =)

代码如下:

\n

1 个答案:

答案 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")