python - 在文件中逐行编辑 - 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"])
解决方案
该行将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")
推荐阅读
- javascript - Javascript - 从另一个函数中回调与调用函数
- java - 我在线程“main”java.lang.SecurityException 中有异常:Manifest main 属性的签名文件摘要无效
- python-3.x - Python Aps Scheduler 在两个工作日之间间隔运行并安排两个作业
- javascript - Javascript dataURL POST到PHP不起作用
- perl - 从 CPAN 安装模块时无法识别 dmake 命令
- python - 在 cmd 上使用 matplotlib 时突然出现 Qt 错误
- linux - 如何防止在 BASH 中第一次成功后运行第二个脚本
- javascript - 尝试使用 axios 从 Reactjs 组件发送数据以表达应用程序
- c++ - 如何将 int/float 可变参数推入向量
? - google-chrome - 拒绝在框架中显示 LOCALHOST,因为“X-Frame-Options”设置为“sameorigin”