【问题标题】:Create directories and populate with phython files创建目录并使用 python 文件填充
【发布时间】:2020-05-03 00:08:13
【问题描述】:

我有一个txt文件,配置如下:

---01---2125---1648---
random words
random words
---01---3068---1648---
random words
random words
---02---3068---1648---
random words
random words

目标是创建一个目录,并根据其所属目录在该目录中插入文件。所有这些都使用文件 data_base.txt 中给出的名称。示例:

data_base
|_01/
|  |_2125.txt
|  |_3068.txt
|
|_02/
|  |_3068.txt
|

等等... txt 文件将用它们各自的随机词填充。代码如下:

import glob, os
from os.path import isfile

path = "/Users/text"
os.mkdir(path)
fp = open("data_base.txt", 'r', -1)
codes = fp.readlines()
for i in codes:
    print(i.replace("---"," ").strip())

我能够使用替换功能删除数字之间的字符串“---”。问题是我没有通过搜索将是目录名称的字符串(01、02 等)来正确理解它。

有谁知道如何将相应的字符串插入为目录名称?

【问题讨论】:

  • Can someone help me? -- 您的最后一句话不是适合 Stack Overflow 问题的重点。请您根据您的具体需要重新措辞一下吗?
  • @Prune 好的,这个问题已经足够了。欣赏。

标签: python file directory


【解决方案1】:

逐行读取文件。当你遇到以--- 开头的行时,不要替换那些;而是……

path = line.split("---")

这将返回您想要的字段:path[0] 为空; path[01] 是目录; path[2] 是文件;其余的(显然)对你来说是垃圾。

跟踪您的目录名称。当你得到一个新的目录名时,你必须创建它;否则,您只需添加一个新文件。

这么多应该让你感动;这些步骤中的每一个都在网上其他地方有详细记录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-13
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 2011-07-08
    • 2012-09-13
    相关资源
    最近更新 更多