Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make Python read multiple txt files

I need help with this Python Script
I am a noob to Python, but I really need this to work
I have over 200.txt files all located in different folders and subs, and in each txt file I have 2 codes that need to be edited

This is what I have going now and this works great but I have to rename the script to match the file name

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

f1 = open('(1).txt', 'r')
f2 = open('(1A).txt', 'w')
for line in f1:
    f2.write(line.replace('"aplid": 2147483648', '"aplid": -2147483648'))
f1.close()
f2.close()

This is my goal for the script to read anyfilename.txt in any folder

import glob
import os

for f in glob.glob("*.txt"):
f1 = open('f', 'r')
f2 = open('f', 'w')
for line in f1:
    f2.write(line.replace('"aplid": 2147483648,', '"aplid": -2147483648,'))
    f2.write(line.replace('"orlid": 2147483648,', '"orlid": -2147483648,'))
f1.close()
f2.close()

I made a batch script for this project and it works great, but it’s super slow, it would be faster for me to edit the python script for each txt file lol..

I don’t know if Python can read Folders and subfolders like batch dir /b /s /a-d

I’m sorry for bothering you’ll, but I searched online and I can’t find anything that helps with this and most of it I don’t understand

I keep reading that using a path can help, but this script is going to be placed in several computers so using path is not best

>Solution :

You can use os.walk to traverse through a directory tree:

import os

for root, dirs, files in os.walk('.'):
    for name in files:
        nmin = os.path.join(root,name)
        with open(nmin,"r") as fin:
            data = fin.read()
        data = data.replace('"aplid": 2147483648,', '"aplid": -2147483648,') \
                   .replace('"orlid": 2147483648,', '"orlid": -2147483648,')
        with open(nmin,"w") as fout:
            fout.write(data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading