如何使用python将txt文件生成到单独的目录中?

问题描述

这是我的代码

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)

这是我得到的输出

enter image description here

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

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

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

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

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

我将不胜感激任何帮助。提前致谢!

解决方法

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

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
,

可能有帮助

import os

pwd = os.getcwd()

playlist_links = ['A',]

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,encoding="utf8") as out_file:
        out_file.write(link)

我认为没有必要调用 os.chdir()

enter image description here