在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 --> Invertern")
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"])

with open("combos.txt", "w")将通过覆盖来擦除当前文件的内容。

你需要选择

  • 写入其他文件,然后删除原始文件并重命名新文件,或者
  • 将整个文件读取到一个列表/string/whatever中,关闭它并处理写入到新创建的同名文件中的数据

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

最新更新