python在每个子文件夹中创建一个文件

时间:2019-03-21 11:30:25

标签: python

我需要帮助! 我需要创建10个子目录:A1,A2,...,A10。每个子目录包含一个名为 position 的文件,其内容为:

2.22222  0.44444  1.58810
5.77778  1.5556  0.41190

每个文件的末尾包含一个与子目录相对应的位置: 例如: 在目录A1中的位置:

2.22222  0.44444  1.58810
5.77778  1.55556  0.41190
1.00000  1.00000  1.00000
目录A2中的

位置包含

2.22222  0.44444  1.58810
5.77778  1.55556  0.41190
2.00000  2.00000  2.00000

在目录A3中的相似位置包含:

2.22222  0.44444  1.58810
5.77778  1.55556  0.41190
3.00000  3.00000  3.00000

以此类推。我尝试通过python进行编码,但是当出现错误时它无法正常工作 IOError:[Errno 21]是目录:

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)

请帮助我调试此代码!

3 个答案:

答案 0 :(得分:1)

您的第一个for循环在“ for i in range(0,10)”位之后需要一个冒号。

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

有可能成为

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

我认为我唯一可以看到的错误是冒号。

num += 1 

所做的事情与您所做的完全相同,这是一种很好且更快的编码方法。您的缩进也不正确,因此如果您也将其整理出来,那应该没问题。

答案 1 :(得分:0)

它可以在我的机器上工作。

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))

答案 2 :(得分:0)

pathlib使得它更容易思考,因为它完成了所有自身路径名的连接。此代码片段将创建目录(如果不存在)并创建文件(如果文件不存在),并将2.00000 2.00000 2.00000...字符串附加到每个目录中。

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)