从fi解析路径列表

2024-09-27 21:32:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个简单的python脚本,它为我提供了子文件夹的绝对路径列表和给定目录的子文件夹的子文件夹列表。然后将列表写入文件。我的下一个目标是以某种方式解析该文件,以便操纵目录(chmod、chgrp等)的权限。你知道吗

下面是一个带有一些(MS-Windows)路径的文件片段,但实际上我将在Unix机器上使用它

C:\Users\Me\Desktop\gopro\New folder\1
C:\Users\Me\Desktop\gopro\New folder\2
C:\Users\Me\Desktop\gopro\New folder\3
C:\Users\Me\Desktop\gopro\New folder\4

我很感激你能想出最好的办法。我是个Python新手,所以请记住这一点。你知道吗


Tags: 文件目录脚本文件夹目标列表new方式
2条回答

既然您提到了mswindows,就可以使用subprocess.run,它基本上在shell中运行命令。你知道吗

import subprocess

with open("somefile.txt") as txtfile:
    for each_path in txtfile.readline():
        subprocess.run(
            ["chmod", "777", each_path],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            shell=True,
        )

我可能误解了这个问题,但我认为如果您想在目录上运行shell命令,这就是您要寻找的:


import os # this is insecure, so USE WITH CAUTION (never in production). 

with open('list_of_directories.txt') as f:
    for folder_name in f.readlines(): # read each line from the file.
        os.system("chmod 777 {}".format(folder_name)) # os.system lets you run shell commands.
        # ...

请注意操作系统()是解决问题最简单的方法,它是非常不安全的。千万不要在生产脚本上使用它,但是对于快速实用程序脚本来说,它是很好的,因为我认为这是您的用例。你知道吗

相关问题 更多 >

    热门问题