Linked Questions

Popular Questions

Re-Naming Files as they are being opened in Python For Loop

Asked by At

I'm trying to create a program that will read in multiple .txt files and rename them in one go. I'm able to read them in, but I'm falling flat when it comes to defining them all.

First I tried including an 'as' statement after the open call in my loop, but the files kept overwriting each other since it's only one name I'm defining. I was thinking I could read them in as 'file1', 'file2', 'file3'... etc

Any idea on how I can get this naming step to work in a for loop?

import os
os.chdir("\\My Directory")

#User Inputs: 
num_files = 3 

#Here, users' actual file names in their directory would be 'A.txt', 
'B.txt', 'C.txt'
filenames = [A, B, C]

j = 1
for i in filenames:
   while j in range(1,num_files):
      open(i + ".txt", 'r').read().split() as file[j]
      j =+ 1

I was hoping that each time it read in the file, it would define each one as file#. Clearly, my syntax is wrong because of the way I'm indexing 'file'. I've tried using another for loop in the for loop, but that gave me a syntax error as well. I'm really new to python and programming logic in general. Any help would be much appreciated.

Thank you!

Related Questions