Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中无限期地创建和写入文件?_Python - Fatal编程技术网

如何在Python中无限期地创建和写入文件?

如何在Python中无限期地创建和写入文件?,python,Python,我必须制作一个脚本,在每个主文件夹(dir1、dir2和dir3)中创建一定数量的子文件夹。然后,在每个子文件夹中,必须不断创建文件(.txt.exe),直到我(用户)决定停止程序为止。现在,我可以在每个主文件夹中创建子文件夹(从0到99),但我不知道如何创建.txt文件。如有任何建议或想法,将不胜感激。这是我的密码: import os folders = ["dir1", "dir2", "dir3"] count = 0 for folder in folders: for

我必须制作一个脚本,在每个主文件夹(dir1、dir2和dir3)中创建一定数量的子文件夹。然后,在每个子文件夹中,必须不断创建文件(.txt.exe),直到我(用户)决定停止程序为止。现在,我可以在每个主文件夹中创建子文件夹(从0到99),但我不知道如何创建.txt文件。如有任何建议或想法,将不胜感激。这是我的密码:

import os

folders = ["dir1", "dir2", "dir3"]
count = 0

for folder in folders:

    for count in range(100):
        subfolder = str(count)
        newfolder =  os.makedirs(os.path.join(folder, subfolder))
我正试着做这样的事情

with open("%s/01.txt" %count, "wa") as fh

因此,它进入每个子目录并创建文件

,您只需打开并不写入任何内容即可。例如:

with open("01.txt", "w") as fh:
    fh.write("")

这意味着,如果有必要,你将来也可以写东西。可能不需要.write(),但它提高了可读性。

我相信你甚至不需要
。write
,你可以
通过
,因为
打开
将创建一个不存在的文件。好的,我会检查一下,但写什么都不会让它读得更好:查看代码的人可以确切地看到它的功能