如何在python中将文本文件中列出的文件从一个文件夹移动到另一个文件夹 [英] How to move files listed in a text file from one folder to another in python

查看:66
本文介绍了如何在python中将文本文件中列出的文件从一个文件夹移动到另一个文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也尝试在 Python 中创建一个脚本来读取文本文件.在文本文件的每一行上,都有一个文件名.我希望脚本循环遍历文本文件的每一行,并将带有文件名的文件从循环所在的当前行,从它的源文件夹移动到特定目标.

I'm attempting too create a script in Python that reads through a text file. On each line of the text file, there's a file name. I want the script to cycle through each line of the text file and move the file with the file name from the current line it's cycled on, from it's source folder to a specific destination.

希望这段代码能更准确地说明我要做什么:

Hopefully this code gives a more accurate idea as to what I'm trying to do:

import shutil

dst = "C:\\Users\\Aydan\\Desktop\\1855"

with open('1855.txt') as my_file:
    for line in my_file:
        src = "C:\\Users\\Aydan\\Desktop\\data01\\BL\\ER\\D11\\fmp000005578\\" + line
        shutil.move(src, dst)

我正在考虑将具有特定文件名的文件内容放入一个数组中,但我最终有 62700 多个可能的文件名,所以我在想它是否只是在循环到每个文件时移动文件行,它会更有效一点?

I was thinking of putting the contents of the file with the specific file names into an array, but I have 62700+ possible file names to end up with, so I was thinking if it just moved the files as it cycled onto every line that it would be a tad more efficient?

我也有使用迭代器(或任何你称之为)的想法,设置 i=[文本文件中的行数],然后让它以这种方式滚动,但看起来好像使用了 for line inmy_file: 我认为只使用 line 是有意义的.

I also had the idea of using an iterator (or whatever you call it) setting i=[number of lines in the text file], then make it scroll that way, but seeing as if used for line in my_file: I thought it would make sense to use just line.

对于测试,文本文件包含:

For a test, the text file contains:

BL_ER_D11_fmp000005578_0001_1.txt
BL_ER_D11_fmp000005578_0002_1.txt
BL_ER_D11_fmp000005578_0003_1.txt

我对这段代码的问题是它没有按预期工作,我没有收到任何错误,但是文件从一个文件夹到另一个文件夹的移动没有​​发生.如果你们能指出这个问题的解决方案,我很乐意.

The problem I'm having with this code is that it's not working as intended, I don't get any errors but the movement of files from one folder to another isn't happening. I would like it if you guys could possible point out a solution to this problem.

谢谢!

艾丹

推荐答案

我会尝试:

import os

dst = "C:\\Users\\Aydan\\Desktop\\1855\\" # make sure this is a path name and not a filename

with open('1855.txt') as my_file:
    for filename in my_file:
        src = os.path.join("C:\\Users\\Aydan\\Desktop\\data01\\BL\\ER\\D11\\fmp000005578\\", filename.strip() ) # .strip() to avoid un-wanted white spaces
        os.rename(src, os.path.join(dst, filename.strip()))

这篇关于如何在python中将文本文件中列出的文件从一个文件夹移动到另一个文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆