0

I have a list of filenames in the file filenames.txt. I am opening all the files one by one, and want to write the result of some operation to a different directory but with the same file name. So far, I tried this, but this won't work. Any help?

with open("/home/morty/filenames.txt","r") as f:
    names = [name.strip() for name in f]

for name in names:
    save=open("/home/morty/dir/%name" %name,"w")
    save.write(---some operation---)

My question is similar to this, but I don't want the files named by count/enumerate. I want the names to be the same as the input file name: Write output of for loop to multiple files

1 Answer 1

1

Your format statement is incorrect. It should be "/home/morty/dir/%s" %name

But when you want to join a directory name with a file name, best is to use os.path.join like this:

for name in names:
    with open(os.path.join("/home/morty/dir",name),"w") as save:
       save.write(---some operation---)

(and a with context block to make sure that the file is closed when done)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.