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

2024-10-01 15:37:11 发布

您现在位置: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')

Tags: ofthepathname目录txtformatopen
1条回答
网友
1楼 · 发布于 2024-10-01 15:37:11
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(一个变量)

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

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

相关问题 更多 >

    热门问题