Binh Thien
Binh Thien

Reputation: 395

python create a file in each subfolder

I need a help! I need to create 10 subdirectories: A1, A2, ...,A10. Each subdirectory contains a file named position with a content:

2.22222  0.44444  1.58810
5.77778  1.5556  0.41190

The end of each file contains a position corresponding to subdirectory: For example: position in directory A1:

2.22222  0.44444  1.58810
5.77778  1.55556  0.41190
1.00000  1.00000  1.00000

position in directory A2 contains

2.22222  0.44444  1.58810
5.77778  1.55556  0.41190
2.00000  2.00000  2.00000

Similar to position in directory A3 contains:

2.22222  0.44444  1.58810
5.77778  1.55556  0.41190
3.00000  3.00000  3.00000

And so on. I tried to code by python but it did not work well when error appeared IOError: [Errno 21] Is a directory:

import os
content += u"0.22222  0.44444  0.58810"
content += u"0.77778  0.55556  0.41190" 
num = 0
for i in range(0, 10)
   num = num + 1
   subdirectory = str("A")+str(num)
   os.mkdir (subdirectory)
   filename = str(position)
   for ip in open(filename):
   with open (os.path.join(subdirectory)) as ip:
   fp.write(content)
   for ip in open(filename):
      with open (os.path.join(subdirectory)) as ip:
          ft.write"{:.5f}  {:.5f}  {:.5f} ".format(num, num, num)

Please help me to debug this code!

Upvotes: 0

Views: 84

Answers (3)

Aaron Ciuffo
Aaron Ciuffo

Reputation: 913

pathlib makes this much easier to think about as it does all the joining of path names it's self. This code snip will make the directories if they don't exist and create a file (if it doesn't exist) and append 2.00000 2.00000 2.00000... strings into each.

from pathlib import Path
dirnames = {'A01': 1, 'A02': 2, 'A03': 3, 'A10': 10}
basePath = Path('./foobar') # base path to work in
myFile = Path('file.txt') # name of each file to append to
repeats = 4 # number of times to repeat the appended value string
for name, value in dirnames.items():
    # Create the file    
    myName = Path(basePath/name)

    # Make the directories
    try:
        myName.mkdir()
    except FileExistsError:
        print('{} exists, skipping'.format(myName))

    # make the string that will be appended to each file
    myString = ''
    print(myFile)
    for i in range(0, repeats):
        myString = myString + ('{:.5f} '.format(value))
    myString + '\n'

    fileName = Path(myName/myFile) # set the file name 

    # write the string out to the file
    with fileName.open(mode='a') as dataOut:
        dataOut.write(myString)

Upvotes: 0

Maged Saeed
Maged Saeed

Reputation: 1885

It works in my machine.

import os
dir_path = os.path.dirname(os.path.realpath(__file__))
# print(dir_path)     #here, you will choose the working directory. currently, it is the same as your python file.
# for readibility, you can use multi-line string here.
content = '''
2.22222  0.44444  1.58810
5.77778  1.5556  0.41190
'''
for i in range(0, 10):
   foldername = dir_path+"\\"+'a'+str(i+1)
   os.makedirs(foldername)
   # use encoding 'utf-8' if you would like so.
   with open(foldername+"\\position.txt",'w',encoding='utf-8') as 
       innerfile:
       innerfile.write(content)
       innerfile.write('{:.5f}  {:.5f}  {:.5f}'.format(i+1,i+1,i+1))

Upvotes: 0

NotEvenTheRain
NotEvenTheRain

Reputation: 113

your first for loop needs a colon after the "for i in range (0, 10)" bit.

for i in range(0, 10)
   num = num + 1

could become

for i in range (0, 10):
    num += 1

that missing colon is the only error I think I can see.

num += 1 

does the exact same thing as what you've done, it's just nice and quicker way to code it. Your indentation is also incorrect, so if you sort that out too it should be okay.

Upvotes: 1

Related Questions