0

这是我的代码

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 文件夹中

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

我将不胜感激任何帮助。先感谢您!

4

2 回答 2

1

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

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
于 2021-05-31T08:05:00.283 回答
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()

在此处输入图像描述

于 2021-05-31T08:43:41.990 回答