有没有一种方法可以取代~&引用;带“的符号~\";在使用python脚本的文本文件中

有没有一种方法可以取代~&引用;带“的符号~\";在使用python脚本的文本文件中,python,python-3.x,Python,Python 3.x,我在一个文件夹里有一大堆文本文件。现在我需要将“~”符号替换为“~\n” 使用python脚本从所有文本文件 我知道这可以在记事本++中实现,我需要将“~”符号放在查找内容和“~\n”替换为部分中,我需要检查可用的扩展选项并单击全部替换。但我需要一个接一个地做 我使用“\n”只是将单行分隔为多行,“~”是我的分隔符 因此,如果有人给我一个python脚本,让我一次对所有文件执行相同的操作,那就太好了。我找到了一种方法,下面是我的完整代码 text = "hi ~ uo~ ~~"

我在一个文件夹里有一大堆文本文件。现在我需要将“~”符号替换为“~\n” 使用python脚本从所有文本文件

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

我使用“\n”只是将单行分隔为多行,“~”是我的分隔符


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

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

text = "hi ~ uo~ ~~"

i = text.replace("~", "~\n")

print(i)
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

假设您有这样一个目录:

。
├── doc1.txt
├── doc2.txt
├── doc3.txt
├── doc4.txt
└── main.py
现在,如果您希望浏览所有文本文件并将所有“~”替换为“~\n”。 为此,请在python中粘贴以下代码

导入操作系统
directory=os.listdir()
对于目录中的文件:
如果文件中有“.txt”:
打开(文件“r”)作为临时文件:
temp=temp_file.read()
温度=温度替换(“~”,“~\n”)
打印(f“在[{file}]中用“~\\n”替换“~”)
打印(f“替换示例:{temp}”)
打开(文件“w”)作为打开的文件:
打开的_文件。写入(临时)
其他:
打印(f“跳过{file}[不是文本文件]”)

欢迎来到stackoverflow!请拿起,仔细阅读并提供。