【问题标题】:how to copy the name of the folders如何复制文件夹的名称
【发布时间】:2014-09-02 11:43:14
【问题描述】:

我是 python 新手,我真的想完成一个简单的任务。我正在尝试仅将某些文件夹的名称复制到另一个文件夹(例如:folderA)。我不关心这些文件夹的内容,我只关心复制它们的名称。

(我要复制的文件夹名称在batch_2016下:sin_1008100、sin_1010987、sin_10109) 以下是我写的,但没有按预期工作

batch_path = '/net/storage/batch_2016' # where the folders are located
batch_name = raw_input("batch name: ") # im giving a new folder name
os.chdir(batch_path)
print(os.getcwd())

for fName in os.listdir('.'):
    if fName.startswith("sin"):
        os.makedirs(batch_name)
        os.chdir(batch_name)
        os.makedirs(fName)

我没有收到任何错误消息,但是当它运行时,它会创建 3 个 batch_name 文件夹,每个文件夹都有我要复制的 folder_names。 所以如果新的文件夹名称是FolderA,它里面有

FolderA, sin_1008100
FolderA, sin_1010987
FolderA, sin_10109

我猜这是因为循环,但我不知道如何解决这个问题。 任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: python if-statement copy directory names


    【解决方案1】:

    我认为这是你想要的:

    import os
    
    batch_path = '/net/storage/batch_2016' # where the folders are located
    batch_name = raw_input("batch name: ") # im giving a new folder name
    os.chdir(batch_path)
    print(os.getcwd())
    
    os.makedirs(batch_name)
    
    for fName in os.listdir('.'):
        if fName.startswith("sin"):
            os.makedirs(batch_name + "/" + fName)
            # alternatively, os.makedirs("../" + batch_name + "/" + fName)
    

    【讨论】:

    • 是的,它有效!这就是我一直在寻找的,谢谢。顺便问一下,“/”是什么意思?
    • “/”是路径的一部分 - 您将在目录 batch_name 中创建一个名为 fName 的文件。例如,使用 batch_name="/net/storage/greatbatch" 和 fName="sin_42",您会得到 /net/storage/greatbatch/sin_42。
    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 2013-04-12
    • 1970-01-01
    • 2018-09-06
    • 2019-03-28
    • 2021-12-28
    • 1970-01-01
    • 2021-05-15
    相关资源
    最近更新 更多