Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.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(Windows)的内容_Python_Windows - Fatal编程技术网

删除特殊目录Python(Windows)的内容

删除特殊目录Python(Windows)的内容,python,windows,Python,Windows,我有相当基础的Python知识,不幸的是,它太基础了,我不知道如何做我想做的事情。我做了一些搜索,找到了我问题的一半答案 计划是删除文件夹的内容,但由于用户名不同,系统之间的目录不同。假设目录为“C:\Users\USER\Documents\VideoEditor\JunkFiles”,但我希望我的程序能够尝试删除所有不同版本的文件。下面是一个示例列表: 'C:\Users\USER\Documents\VideoEditor09\JunkFiles' 'C:\Users\USER\Docum

我有相当基础的Python知识,不幸的是,它太基础了,我不知道如何做我想做的事情。我做了一些搜索,找到了我问题的一半答案

计划是删除文件夹的内容,但由于用户名不同,系统之间的目录不同。假设目录为“C:\Users\USER\Documents\VideoEditor\JunkFiles”,但我希望我的程序能够尝试删除所有不同版本的文件。下面是一个示例列表: 'C:\Users\USER\Documents\VideoEditor09\JunkFiles' 'C:\Users\USER\Documents\VideoEditor10\JunkFiles' 'C:\Users\USER\Documents\VideoEditor11\JunkFiles'

所以基本上

无论用户名是什么,我如何告诉它目录在哪里? 我如何告诉它删除指定目录的内容,但保留文件夹(如果可能)

谢谢


西奥。您可以尝试以下几点:

import os
user = 'some_user_name'
videoEditors = ['VideoEditor09','VideoEditor10','VideoEditor11']
for i in videoEditors:
    os.chdir('C:\Users\%s\Documents\%s\JunkFiles'%(user,i))
    files = os.listdir('.')
    for file in files:
        os.remove(file)
我在这里使用的主要内容是和一个需要浏览的文件夹列表。同时“%s”也是Python的一部分


希望这有帮助

您可以如下方式访问用户的文档目录:

>>> import os
>>> documents = os.path.join(os.environ['USERPROFILE'], 'Documents')
>>> documents
'C:\\Users\\poke\\Documents'
>>> directories = [os.path.join(documents, 'VideoEditor{0}\\JunkFiles'.format(y)) for y in ('09', '10', '11')]
>>> directories
['C:\\Users\\poke\\Documents\\VideoEditor09\\JunkFiles', 'C:\\Users\\poke\\Documents\\VideoEditor10\\JunkFiles', 'C:\\Users\\poke\\Documents\\VideoEditor11\\JunkFiles']
然后,您可以循环浏览目录中的文件以删除它们,或者如果删除文件夹也可以(您可以在以后再次创建它们),您也可以使用:


那么,您的文件夹是否始终采用上述格式,但用户名是否已更改?因此,我的文件夹将是:“C:\Users\jonathanV\Documents\VideoEditor09\JunkFiles”
import os import shutil Documents=os.path.join(os.environ['USERPROFILE'],'Documents')Documents'C:\\Users\\poke\\Documents'目录=[os.path.join(Documents,'VideoEditor{0}\\JunkFiles.)。格式(y)),在('09','10','11')]目录中目录中的目录[C:\\Users\\poke\\Documents\\VideoEditor09\\JunkFiles',[C:\\Users\\poke\\Documents\\VideoEditor10\\JunkFiles',[C:\\Users\\poke\\Documents\\VideoEditor11\\JunkFiles']shutil.rmtree(directory)
工作,但只检查第一个文件夹(09)而不是其他的。有了这个,我每次给别人使用的时候都必须输入用户名吗?在这个设置中,你可以创建一个用户列表,并循环这些用户,就像我使用视频编辑器一样。
>>> import shutil
>>> for directory in directories:
        shutil.rmtree(directory)
>>> os.path.expanduser('~')
'C:\\Users\\falsetru'