Shane Nicholson
Shane Nicholson

Reputation: 75

How do I loop through directory and save every text file in Python

I have created the following code that reads every text file in a directory. When I save the file to lido1 it only saves the last text file in the directory. How do I create a text file for every file in Lido?

import os
import uuid

unique = str(uuid.uuid4())

for root, dirs, files in os.walk(r"C:\Users\shane\Desktop\Lido"):
   for file in files:
       if file.endswith(".txt"):
           filename = os.path.join(root, file) 

           with open(filename) as f:
               text = f.read()
               file = open('C:\\Users\\shane\\Desktop\\lido1\\'+ 
               unique +'.txt',"w")
               file.write(text)
               file.close()

Upvotes: 0

Views: 902

Answers (1)

Shane Nicholson
Shane Nicholson

Reputation: 75

import os
import uuid

unique = str(uuid.uuid4())

for root, dirs, files in 
os.walk(r"C:\Users\shane\Desktop\Lido"):
   for file in files:
       if file.endswith(".txt"):
        filename = os.path.join(root, file) 
        unique = str(uuid.uuid4())

        with open(filename) as f:
            text = f.read()
            print(text)
            file = open('C:\\Users\\shane\\Desktop\\lido1\\'+ unique +'.txt',"w")
            file.write(text)
            file.close()

Upvotes: 1

Related Questions