Use the python loop to create multiple files

  • 2021-01-02 21:56:29
  • OfStack

Problem: Place each row of data in Excel into an txt document.

Answer: You must open the file with open(' XXX.txt ') before writing to the file with python, but you cannot iterate over the variables in quotes "". After searching, it was found that string type variables could be put into open(). And that solves the problem.

The code is as follows:


i=1
ll=['a','b','c','e','f']
for it in ll : 
 i_str=str(i)
 filename=i_str+'.txt'
 f=open( filename,'w')

 f.write("something")
 f.close()
 i=i+1

Related articles: