【问题标题】:How do I generate txt files into separate directories with python?如何使用 python 将 txt 文件生成到单独的目录中?
【发布时间】:2021-08-18 12:46:36
【问题描述】:

这是我的代码

import os

pwd = os.getcwd()

playlist_links = ['A', 'B', 'C', 'D', 'E', 'F',]

for link in playlist_links:
    # Create the path
    path = os.path.join(pwd, link)

    # Create the directory
    if not os.path.exists(path):
        os.mkdir(path)

    os.chdir(path)

    with open("Z:/www.rttv.com/Change_Into_Dir_TEST/single-video-v5-{}.txt".format(link), 'w', encoding="utf-8") as output_file:
        output_file.write(link)

    os.chdir(pwd)

这是我得到的输出:

我想要的是将每个 txt 文件放在其受尊重的文件夹中。例如:

single-video-v5-A.txt 应该在 A 文件夹中

single-video-v5-B.txt 应该在 B 文件夹中

single-video-v5-C.txt 应该在 C 文件夹中

等等等等…… 我的代码到底有什么问题?

我将非常感谢任何帮助。提前谢谢!

【问题讨论】:

  • 您没有将占位符作为文件夹包含在路径中,而是将其放在文件名的末尾...

标签: python arrays loops directory with-statement


【解决方案1】:

可能会有帮助

import os

pwd = os.getcwd()

playlist_links = ['A', 'B', 'C', 'D', 'E', 'F',]

for link in playlist_links:
    # Create the path
    path = os.path.join(pwd, link)

    # Create the directory
    if not os.path.exists(path):
        os.mkdir(path)

    save_file = f'single-video-v5-{link}.txt' # create the file name
    save_path = os.path.join(path,save_file)  # create the save_path using above file name

    # open the file write it and close
    with open(save_path, 'w', encoding="utf8") as out_file:
        out_file.write(link)

我认为不需要调用 os.chdir()

【讨论】:

    【解决方案2】:

    你应该看看这个逻辑,变化是微妙的,但效果是至关重要的:

    import os
    pwd = os.getcwd()
    playlist_links = ['A', 'B', 'C', 'D', 'E', 'F',]
    
    for link in playlist_links:
        path = os.path.join(pwd, link)
        if not os.path.exists(path):
            os.mkdir(path)
        os.chdir(path)
        
        with open(f"single-video-v5-{link}.txt", 'w', encoding="utf-8") as output_file:
            output_file.write(link)
        
        os.chdir(pwd)
    

    执行后,检查当前工作目录的内容,然后是A/目录的内容:

    $ ls
    A  B  C  D  E  F  p.py
    $ ls A/
    single-video-v5-A.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-25
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      相关资源
      最近更新 更多