【问题标题】:Access and copy files to new directory using Python使用 Python 访问文件并将其复制到新目录
【发布时间】:2018-11-22 17:08:46
【问题描述】:

我有一个包含文件路径列表的文本文件,我想用 Python 访问它,复制并粘贴到一个新文件夹中。

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

所有文件都应该被复制并粘贴到一个新文件夹(output_folder)中。我怎样才能做到这一点?

到目前为止我的代码:

for filename in textfile:
    text=filename.read()
    for line in text:
        line=filepath
          #move filepath?

【问题讨论】:

标签: python file-io directory copy-paste


【解决方案1】:

我认为您可以使用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 错误,请注释创建输出文件夹的行并在工作目录中手动创建它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 2012-03-18
    • 2014-09-22
    • 2019-11-01
    相关资源
    最近更新 更多