编辑多个文本文件的脚本

2024-04-25 04:19:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个c++程序,它生成许多数据文件,每个文件包含三列。现在在每一个数据文件中,第三列可能有-nan的异常条目。如何编写一个脚本,以便它打开这些数据文件中的每一个,并找到第三列中包含nan的所有行并删除所有这些行? 有没有可能用bash或python编写一个可以做到这一点的脚本? 示例:

100   0.1    15.8334
100   0.2    16.7895
100   0.3     -nan
100   0.4    15.8543
100   0.5      -nan

在这个文件中,我想删除第3行和第5行,这样我的文件看起来像

^{pr2}$

Tags: 文件程序脚本bash示例数据文件条目nan
3条回答
sed -i -e '/-nan/d' datafile.txt

要对多个文件进行操作,可以替换“数据文件.txt“使用匹配所有文件的glob,或使用for循环

^{pr2}$

或者find命令:

find . -name "data*.txt" -exec sed -i -e '/-nan/d' {} +

这是基本机制:

with open('yourfile.txt') as fin, open('yourfile_output.txt', 'w') as fout:
    for line in fin:
        try:
            c1, c2, c3 = line.split()
            if c3 != '-nan':
                fout.write(line)
        except ValueError as e:
            pass # Handle cases where number of cols != 3

然后把它放到函数中使用球.iglob重新生成匹配文件名和循环的列表。。。

另一个可能的选择只是为了完整性:

^{pr2}$

比如(在bash中):

for file in files ;do
  grep -v   -nan file > file.$$ && mv file.$$ file
done

但应该在代码中清理它。

相关问题 更多 >