Hey there I tried making a loop for creating folders and files. According to me the program should work like this :
and it goes on..... What my program does is :
my program
import os,sys
di=("ab")
a=0
i=0
fi=open("az.txt","w")
def file():
for i in range(0,10):
fi.write(str(i))
def mk():
for a in range(0,10):
os.mkdir(di+str(a))
file()
mk()
please help
Hey there I tried making a loop for creating folders and files. According to me the program should work like this : 1) create 1st folder and 1 file inside it. 2) create 2nd folder and 1 file inside it and it goes on..... What my program does is : 1) create 1 file 2) create folders
Indeed, it does the latter and not the former. What your program does is create directories, and write:
0123456789
ten times inside az.txt
. Your error is that you're opening a file outside of any loop, and then you write to it within a loop.
I guess, that's what you want:
import os,sys
di="ab"
def mk_file(di):
for i in range(0,10):
with open("{}/az_{}.txt".format(di,i), "w") as fi:
fi.write(str(i))
def mk_dir():
for a in range(0,10):
dname = "{}_{}".format(di, str(a))
os.mkdir(dname)
mk_file(dname)
if __name__ == "__main__":
mk_dir()
This script will create a folders with the name "a", "b", "c" and put files 1.txt 2.txt .. 5.txt in each folder.
Make a changes as you need as try it.
import os
for i in "abc":
os.system ("mkdir "+i)
for j in range (5):
os.system ("touch "+str(i)+"/"+str(j)+".txt")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.