有没有办法使用 python 脚本将文本文件中"~"符号替换为"~n"符号



我在一个文件夹中有一组巨大的文本文件。现在我需要替换"~"带有"~\n〃;使用python脚本从所有文本文件

我知道这可以在记事本++中实现,我需要把"~"查找内容"中的符号~\n〃;替换为部分,我需要检查可用的扩展选项,然后单击全部替换。但我需要一个接一个地做。

我正在使用";\n〃;只是为了将单条线分成多条线~"是我的分隔符吗

因此,如果有人给我一个python脚本,让我一次性对所有文件执行同样的操作,那就太好了。

text = "hi ~ uo~ ~~"
i = text.replace("~", "~n")
print(i)

假设您有一个这样的目录:

.
├── doc1.txt
├── doc2.txt
├── doc3.txt
├── doc4.txt
└── main.py

现在,如果你想浏览所有的文本文件~"用"~\n〃;。要做到这一点,请在python 中粘贴以下代码

import os
directory = os.listdir()
for file in directory:
if ".txt" in file:
with open(file, "r") as temp_file:
temp = temp_file.read()
temp = temp.replace("~", "~n")
print(f"Replacing '~' with '~\n' in [{file}]")
print(f"Replaced example: {temp}")
with open(file, "w") as opened_file:
opened_file.write(temp)
else:
print(f"Skipped {file} [Not a text file]")

我已经找到了一种方法,下面是我对同一的完整代码

import os
from tkinter import Tk, filedialog
root = Tk() # pointing root to Tk() to use it as Tk() in program.
root.withdraw() # Hides small tkinter window.
root.attributes('-topmost', True) # Opened windows will be active. above all windows despite of selection.
cwd = filedialog.askdirectory() # Returns opened path as str
path = os.path.join(cwd, "converted_file")
try:
os.stat(path)
except:
os.mkdir(path)
for filename in os.listdir(cwd):
if os.path.isfile(os.path.join(cwd, filename)):
with open(os.path.join(path, filename), 'w') as f:
t = open(filename, 'r')
t_contents = t.read()
t_contents = t_contents.replace("~", "~n")
f.write(t_contents)
print(filename)
else:
continue

最新更新