使用Python访问文件并将其复制到新目录

时间:2018-11-22 17:08:46

标签: python file-io directory copy-paste

我有一个文本文件,其中包含文件路径列表,我想使用Python访问这些文件,然后将其复制并粘贴到新文件夹中。

const db = require("mongoose");
const User = require("./models/user");

router.post("/addusers", async (req, res, next) => {

    const SESSION = await db.startSession();

    await SESSION.startTransaction();

    try {

          const newUser = new User({
            //*** data for user ***
          });
          await newUser.save();

          //*** for test purpose, trigger some error ***
          throw new Error("some error");

          await SESSION.commitTransaction();

          //*** return data 

    } catch (error) {
            await SESSION.abortTransaction();
    } finally {
            SESSION.endSession();
    }    

 });

所有文件都应复制并粘贴到新文件夹(output_folder)中。我该如何实现?

到目前为止,我的代码:

The file path list looks like this:
filepath1
filepath2
...

1 个答案:

答案 0 :(得分:0)

我认为您可以使用shutil.copy函数来实现您的目标。会是这样的:

import shutil
import os

absolute_path = os.getcwd() # Stores original path.

os.makedirs("/output_folder") # Creates output_folder. 

with open("filepaths.txt") as file:
    for filepath in file.readlines():
        path = filepath[:filepath.rfind("/")] # Extracts folder.
        os.chdir(path) # Changes directory.
        filename = filepath[filepath.rfind("/") + 1:] # Extracts filename.
        filename = filename.replace("\n","") # Gets rid of newline character.
        shutil.copy(filename, absolute_path + "/output_folder/")

如果出现PermissionDenied错误,请注释创建输出文件夹的行,并在工作目录中手动创建它。