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

如何在python中使用来自不同目录的文件?,python,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_{}_{

我想循环浏览几个目录中的文件。 我在一个目录中有几个目录: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')
我们只需迭代由
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

您编写的代码看起来运行良好。如果没有,可以发布堆栈跟踪吗?如果有,你想做什么,而这段代码没有做?一个快速评论你的代码。在进行更改时,请始终记住打开和关闭文件。最好的方法是使用:添加到前面的注释:使用open('/path/change/fileobs.txt',r')作为filein:#做点什么。在文档中查找
os.walk
with open('path', 'r') as a_file:
    # do your things with the file
# file is closed outside the statement