如何在python中使用来自不同目录的文件?

时间:2018-01-08 18:03:06

标签: python

我想从多个目录中循环文件。 我在一个目录中有几个目录:dir

  import os
  >>> os.listdir('/path/dir/')
  ['Datax', 'Datay',  'BDA', 'RADI']

从第一个目录中读取文件:

   filein= open('/path/Datax/fileobs.txt', 'r') 
   #do something with file…………
   fileout = open('/path/Datax_{}_{}.txt'.format(V4, V5), 'w')# include the name of the directory in the name of the 

现在转到第二个目录Datay并执行相同操作:

    filein= open('/path/Datay/fileobs.txt', 'r') # just change the path to the second directory
    #do something with file…………
    fileout = open('/path/Datay_{}_{}.txt'.format(V4, V5), 'w')# include the name of the directory in the name of the 

等......

更改如下:

         filein= open('/path/change/fileobs.txt', 'r')
         # do something....
         fileout = open('/path/change_{}_{}.txt'.format(V4, V5), 'w')

1 个答案:

答案 0 :(得分:1)

dir_list = os.listdir('/path/dir/')

for a_dir in dir_list:
    filein= open('/path/'+a_dir+'/fileobs.txt', 'r') 
    fileout = open('/path/{}_{}_{}.txt'.format(a_dir,V4, V5), 'w')

我们只是迭代os.listdir('/path/dir/')给出的目录,并在文本中包含变量。在文本中包含变量的方式都在这里,'text'+a_var+'text'text{}text。format(a_var)

确实,您应该在file.close()之后关闭文件或使用with语句:

with open('path', 'r') as a_file:
    # do your things with the file
# file is closed outside the statement