如何创建包含在同一文件夹中的文件的文件列表? [英] How to create a file list of my files included in the same folder?

查看:61
本文介绍了如何创建包含在同一文件夹中的文件的文件列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含numpy文件的文件夹.我需要创建一个numpy列表,在其中放置所有numpy文件名.为此,我使用以下代码:

I have a folder which contains numpy files. I need to create a numpy list where I will put all my numpy file names. For that, I use this code:

import os

a = open('C:\\Users\\user\\My_Test_Traces\\Traces.list_npy', "w")
for path, subdirs, files in os.walk(r'C:\\Users\\user\\CPA_test_1000_Tests\\test'):
   for filename in files:
      f = os.path.join(path, filename)
      a.write(str(f) + os.linesep)  

因此,它为我提供了文件列表及其路径,如下所示:

As a result, it gives me a list of my files and their paths like this:

   C:\\Users\\user\\My_Test_Traces\\ Trace1_Pltx1

   C:\\Users\\user\\My_Test_Traces\\ Trace2_Pltx2

   C:\\Users\\user\\My_Test_Traces\\ Trace3_Pltx3

   C:\\Users\\user\\My_Test_Traces\\ Trace4_Pltx4

但是,我只需要文件名,行之间不需要任何空格:

however , I need only the files name, I don't need any spaces between lines:

   Trace1_Pltx1
   Trace2_Pltx2
   Trace3_Pltx3
   Trace4_Pltx4

推荐答案

也许更好:

import os

folder = 'C:\\Users\\user\\CPA_test_1000_Tests\\test'

with open('C:\\Users\\user\\My_Test_Traces\\Traces.list_npy', 'w') as fp:
    fp.write(os.linesep.join(os.listdir(folder)))

这篇关于如何创建包含在同一文件夹中的文件的文件列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆