首页 > 解决方案 > 在文件中逐行编辑 - Python

问题描述

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

hello:world
learning:python
is:funny

我想将其还原为:

world:hello
python:learning
funny:is

我可以编写脚本来反转单词,但如果文件有更多的一行。例子:

hello:world
learning:python

该脚本删除所有其他行,只留下第一行 hello:world。我尝试使用readlines()功能,\n但对我不起作用。

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

这是代码:

#IMPORTS
import os
import platform
import time
import subprocess

#PUT MODULE 2 IN A NEW WINDOW
if platform.system() == "Windows":
    clear = lambda: os.system('cls')
    clear()

#EXPLANATION MODULE SELECTED
print("You selected module two --> Inverter\n")
time.sleep(1) #TIME LOAD

#USER HAVE TO PUT THE FILE NAMED "COMBOS.TXT"
fname = input("Put your file: ")

if fname == "combos.txt":
    try:
        f = open("combos.txt")
        with open("combos.txt", "r") as infile:
            for line in infile:
                words = line.split(":")[::-1]
                final = ":".join(words)
                with open("combos.txt", "w") as out:
                    out.write(final)
                    print("Done!")
    except:
        print("--Something went wrong while trying to load your file--")

input("Your file was edited successfully! Press enter to continue...")
if platform.system() == "Windows":
    p = subprocess.call(["python", "start.py"])

标签: pythonpython-3.x

解决方案


该行将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")

推荐阅读