【问题标题】:Creating folders from text file从文本文件创建文件夹
【发布时间】:2021-03-30 11:40:53
【问题描述】:

我正在尝试从文本文件的上下文中创建文件夹。

with open("filename.txt", "r") as x:
    for line in x:
        line= line.strip().split()
        filename= "_".join([i for i in line])
        os.mkdir(filename)

只要文件是这样的,这段代码就可以工作;

1
2
3
4

但是我的文本文件包含更多的东西,而且它有“-”字符串,我想在这些文件夹中创建子文件夹。文本文件如下:

1 - a
2 - b
3 - c - d
4 - e - f - g

最后,我希望有 4 个主文件夹(1、2、3、4),在这些文件夹中需要有 a、b、c、d、e、f、g 子文件夹。我正在尝试获取这样的文件夹;

1\a
2\b
3\c\d
4\e\f\g

提前致谢

【问题讨论】:

  • 你好 nespressoX :) 尝试使用 os.mkdir(filename) 代替 os.makedirs()
  • 旁注:[i for i in line] 等价于line...

标签: python


【解决方案1】:

这将创建嵌套目录...

from pathlib import Path
with open("filename.txt", "r") as x:
    for line in x:
        dirs_list = [i.strip() for i in line.split('-')]
        Path(*dirs_list ).mkdir(parents=True, exist_ok=True)

【讨论】:

  • 抱歉打扰了,最后一件事 :) 没有必要做 line.strip() 因为你已经 strip split() 的每个元素(i.strip()
【解决方案2】:

您可以使用os.makedirs() 试试这个

What is different between makedirs and mkdir of os?

import os 

with open('filename.txt','r') as x:
    for line in x.read().splitlines():
        spl = line.strip().split('-')
        directory = os.path.sep.join([s.strip() for s in spl])
        #print(directory)
        os.makedirs(directory)

【讨论】:

    【解决方案3】:

    您可以使用此循环来帮助您解决问题:

    import os
    
    def make_and_ender(folder_name):
        os.mkdir(folder_name)               # Make folder based on folder name given
        os.chdir(folder_name)               # Move into that folder
    
    with open("filename.txt", "r") as x:    # Open file for reading
        content = x.read()                  # Load entire file into 1 large string
        lines = content.splitlines()        # Split into lines
        current_path = os.getcwd()          # Get the current working directory (The folder including 1,2,3,4)
        for line in lines:
            folder_list = line.split(" - ") # Make a list out of the line, splitting the string up based on the-
            for folder in folder_list:      # " - " format (search split up if your not sure )
                folder_name = folder_list[folder_list.index(folder)] # Get the name of the next folder in the list
                make_and_ender(folder_name) # call the function (make_and_enter)
            os.chdir(current_path)          #return to the current path (The folder including 1,2,3,4)
    

    【讨论】:

      猜你喜欢
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      相关资源
      最近更新 更多