Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在文件路径名(Python)中剥离中间文件夹_Python_Path_Os.path - Fatal编程技术网

在文件路径名(Python)中剥离中间文件夹

在文件路径名(Python)中剥离中间文件夹,python,path,os.path,Python,Path,Os.path,我有一个路径/foo/bar/poo/car,目录car中有文件。 我想以/foo/bar结束,在bar中使用相同的文件。我意识到这是错误的,因为它不维护文件: >>> import os >>> os.path.dirname(os.path.dirname('/foo/bar/poo/car')) '/foo/bar' 我想我得先把文件从车里移到酒吧,然后再做上面的事?是否有更干净或更简单的方法执行此操作?使用: 从pathlib导入路径 p=路径('/

我有一个路径
/foo/bar/poo/car
,目录
car
中有文件。 我想以
/foo/bar
结束,在
bar
中使用相同的文件。我意识到这是错误的,因为它不维护文件:

>>> import os
>>> os.path.dirname(os.path.dirname('/foo/bar/poo/car'))
'/foo/bar'
我想我得先把文件从车里移到酒吧,然后再做上面的事?是否有更干净或更简单的方法执行此操作?

使用:

从pathlib导入路径
p=路径('/foo/bar/poo/car')
bar=p.parent.parent
打印(条)
输出:

/foo/bar
要移动文件,请使用。

使用:

从pathlib导入路径
p=路径('/foo/bar/poo/car')
bar=p.parent.parent
打印(条)
输出:

/foo/bar

要移动文件,请使用。

必须首先使用glob获取所有文件的绝对路径。然后可以使用shutil.move移动这些文件

import glob
import os
import shutil


source_dir = r'R:/foo/bar/poo/car'
dest_dir = r'R:/foo/bar'

# get all file path
all_files_path = glob.glob(os.path.join(source_dir, '*.*'))

# move the files to the new dir
for file_path in all_files_path:
    shutil.move(file_path, dest_dir)

必须首先使用glob获取所有文件的绝对路径。然后可以使用shutil.move移动这些文件

import glob
import os
import shutil


source_dir = r'R:/foo/bar/poo/car'
dest_dir = r'R:/foo/bar'

# get all file path
all_files_path = glob.glob(os.path.join(source_dir, '*.*'))

# move the files to the new dir
for file_path in all_files_path:
    shutil.move(file_path, dest_dir)

检查此链接:@CavinDsouza抱歉,我刚刚编辑了问题。检查此链接:@CavinDsouza抱歉,我刚刚编辑了问题。