-1

I have a huge set of text files inside a folder. And now I need to replace the "~" symbol with the "~\n" from all text files using python script

I know this can be achieved in notepad++ where I need to put the "~" symbol in the Find what and "~\n" replace with section and I need to check the extended option available and click on replace all. but I need to do it one by one.

I am using "\n" just to break the single line into multiple lines and "~" is my delimiter

So it would be great if someone gives me a python script to do the same at one shot for all files.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • 1
    https://docs.python.org/3/library/stdtypes.html#str.replace – hiro protagonist May 14 '21 at 09:00
  • 1
    welcome to stackoverflow! please take the [tour](http://stackoverflow.com/tour), read up on [how to ask a question](https://stackoverflow.com/help/asking) and provide the [shortest program necessary to reproduce the problem](https://stackoverflow.com/help/minimal-reproducible-example). – hiro protagonist May 14 '21 at 09:01

3 Answers3

1
text = "hi ~ uo~ ~~"

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

print(i)
Someone
  • 350
  • 3
  • 13
1

Let's say you have a directory like this:

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

Now if you want to go through all of the text files and replace all of the "~" with "~\n". To do that paste the following code in 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]")
Arib Muhtasim
  • 147
  • 2
  • 8
0

I have found a way to this and here is my complete code for the same

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