简体   繁体   中英

Open and move files across multiple directories

I have a bunch of directories, each containing one .txt file, containing a list of filenames i want to move to that directory. So, I want to iterate through each directory, read in the .txt, then copy the names in that same to the same directory containing the text file.

So my original directory is:

original = "path/to/direc"
destination = glob.glob(path + '/*_winning_comparisons_new')

Where the names of the directories of interest contain the string /*_winning_comparisons_new

Each destination contains a single .txt folder, which looks like this:

file1
file2
file3
…

So I want to move the names within the .txt folder to the destination directory. They are located in the original directory.

I wrote the code below to do it

original = "path/to/direc/"
destination = glob.glob(path + '/*_winning_comparisons_new') 

#go to each directory and read the text file. 
for i in destination:
    print(i)
    for filenames in os.listdir(i):
        with open(os.path.join(i, filenames)) as myfile:
            content = myfile.read()
            print(content)

Now, I am stuck on the "copy the filenames in content" part. Any tips on how to do this correctly?

Import shutil at the begin of your program:

import shutil

I guess, i stores the path to the destination folder? Within your with statement do the following:

content = myfile.read().splitlines()
for src_file in content:
    shutil.copy(src_file, i)

Hope, I understood your question correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM