[英]Python functions to move all files and folders to a destination folder
I have a txt file, in which in each line i have the path of files and folders i want to segregate into one place. 我有一个txt文件,在每一行中,我都有要隔离到一个地方的文件和文件夹的路径。
The list is something like this in my list.txt file. 该列表在我的list.txt文件中类似。 Each entry starts off on a new line. 每个条目都从新行开始。
C:\xxx\xxy
C:\abc\def\ghi.pdf
and my destination folder is c:\\users\\mr_a\\dest 而我的目标文件夹是c:\\ users \\ mr_a \\ dest
I want to : 我想要 :
1. move the directory xxy
and all its files and subfolders to dest
1.将目录xxy
及其所有文件和子文件夹移至dest
2. move ghi.pdf
file to dest
. 2.将ghi.pdf
文件移动到dest
。
Do the same for other entries in the list.txt
file. 对list.txt
文件中的其他条目执行相同的操作。 So that my dest
directory would look like: 这样我的dest
目录如下所示:
dest\xxy
dest\ghi.pdf
I looked into shutil
but am not still sure which function to use. 我调查了shutil
但仍不确定要使用哪个功能。 It says that the destination
directory shouldn't be already existing, but in my case its not so. 它说destination
目录不应该已经存在,但是在我的情况下却不存在。 I'm getting confused which methods to use. 我很困惑要使用哪种方法。 Please also mention if the methods you mention are safe (I don't want any nasty cut-n-paste where bits of my files may go missing etc) 还请提及您提到的方法是否安全(我不希望有任何讨厌的cut-n-paste可能会丢失我文件的位等)
What I'm asking is: What methods to use to accomplish what I need to do here? 我要问的是:使用什么方法可以完成我在这里要做的事情?
Edit: And I use Windows, not Linux or any Unix system 编辑:而且我使用Windows,而不是Linux或任何Unix系统
with open('list.txt') as f:
for line in f:
shutil.move(line, dest)
Check out os
and os.path
. os.path
出os
和os.path
。 You will find some useful functions like: 您会发现一些有用的功能,例如:
os.path.exists
- checks whether a path exist (like your destination path) os.path.exists
检查路径是否存在(例如目标路径) os.makedirs
- creates a directory (including missing parent directory) os.makedirs
创建一个目录(包括缺少的父目录) os.path.isdir
, os.path.isfile
- checks whether the path contains a directory or a file. os.path.isdir
, os.path.isfile
检查路径是否包含目录或文件。 os.path.basename
- cuts the filename out of a path os.path.basename
从路径中剪切文件名 os.path.join
- joins paths (or a path with a filename) os.path.join
连接路径(或具有文件名的路径) Here is a code example, I didn't try it: 这是一个代码示例,我没有尝试过:
if not os.path.exists(dest):
os.makedirs(dest)
with open('list.txt', 'r') as f:
for line in f.readlines():
filepath = line.strip()
filename = os.path.basename(filepath)
shutil.move(filepath, os.path.join(dest, filename))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.