python - 如何删除 numpy 列表文件之间的空格行?

标签 python numpy

How to create a file list of my files included in the same folder?我已在此问题中发布,我需要将同一文件夹中的所有 mye 文件名放入一个 numpy 文件中。

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

我使用这个代码并且它可以工作,但是我的文件名之间仍然有空格线,我的意思是我得到的结果如下所示:

   Trace1_Pltx1

   Trace2_Pltx2

   Trace3_Pltx3

   Trace4_Pltx4

但是我必须得到的结果必须如下所示:

   Trace1_Pltx1
   Trace2_Pltx2
   Trace3_Pltx3
   Trace4_Pltx4 

我真的不知道问题出在哪里?

最佳答案

看看os.linesep()您正在调用的方法...

如文档中所述:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

所以,而不是:

fp.write(os.linesep.join(os.listdir(folder)))

尝试:

fp.write('\n'.join(os.listdir(folder)))

或者你甚至可以使用

with open('C:\\Users\\user\\My_Test_Traces\\Traces.list_npy', 'w') as fp:
    for f in os.listdir(folder):
        fp.write(f + "\n")

关于python - 如何删除 numpy 列表文件之间的空格行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42905276/

相关文章:

python - 返回一个只在某些时候使用的对象

python - 在 docker 中运行时,python 脚本无法导入 kafka 库

python套接字保活设置

python - 根据当前用户正在查看的页面检查当前用户

python - 是什么导致我的 Python 程序使用 opencv 耗尽内存?

python - Python 中具有 nan 值的数组之间的平均值

python - 分配给给定行和列索引的 NumPy 数组的网格

python - 来自 groupby 的 Pandas 累积差异

python-3.x - NumPy:linalg.eig()和linalg.eigh()之间的区别

python - 如何在 Python 中对列表运行算法并将结果存储在列表中?