Skip to main content
 首页 » 编程设计

python之使用 Python v3.5 删除多个文本文件中具有相同行开头但不同行结尾的行

2025年05月04日28sxdcgaq8080

我有一个充满 .GPS 文件的文件夹,例如1.全局定位系统,2.全局定位系统等... 每个文件中包含以下五行:

Trace #1 at position 0.004610 
$GNGSA,A,3,02,06,12,19,24,25,,,,,,,2.2,1.0,2.0*21 
$GNGSA,A,3,75,86,87,,,,,,,,,,2.2,1.0,2.0*2C 
$GNVTG,39.0304,T,39.0304,M,0.029,N,0.054,K,D*32 
$GNGGA,233701.00,3731.1972590,S,14544.3073733,E,4,09,1.0,514.675,M,,,0.49,3023*27 

...后跟相同的数据结构,但在接下来的五行中具有不同的值:

Trace #6 at position 0.249839 
$GNGSA,A,3,02,06,12,19,24,25,,,,,,,2.2,1.0,2.0*21 
$GNGSA,A,3,75,86,87,,,,,,,,,,2.2,1.0,2.0*2C 
$GNVTG,247.2375,T,247.2375,M,0.081,N,0.149,K,D*3D 
$GNGGA,233706.00,3731.1971997,S,14544.3075178,E,4,09,1.0,514.689,M,,,0.71,3023*2F 

(我意识到 $GNGSA 行之后的值在上面的例子中没有变化。这只是一个不好的例子......在真实数据集中它们确实不同!)

我需要删除以“$GNGSA”和“$GNVTG”开头的行(即我需要从每个 .GPS 文件中的每组五行中删除第 2、3 和 4 行)。

这种五行模式在每个文件中持续不同次数(对于某些文件,可能只有两个五行组,而其他文件可能有数百个五行组)。因此,根据行号删除这些行是行不通的(因为行号是可变的)。

我遇到的问题(如上例所示)是“$GNGSA”或“$GNVTG”后面的文本不同。

我目前正在学习 Python(我使用的是 v3.5),所以认为这对我来说是一个很好的项目,可以让我学习一些新技巧...

我已经尝试过的:

到目前为止,我已经成功地创建了遍历整个文件夹的代码:

import os 
 
indir = '/Users/dhunter/GRID01/'  # input directory 
for i in os.listdir(indir):  # for each "i" (iteration) within the indir variable directory... 
    if i.endswith('.GPS'):  # if the filename of an iteration ends with .GPS, then... 
        print(i + ' loaded')  # print the filename to CLI, simply for debugging purposes. 
        with open(indir + i, 'r') as my_file:  # open the iteration file 
            file_lines = my_file.readlines()    # uses the readlines method to create a list of all lines in the file. 
            print(file_lines)  # this prints the entire contents of each file to CLI for debugging purposes. 

上面的一切都完美无缺。

我需要什么帮助:

  1. 如何检测并删除行本身,然后保存文件(保存到同一位置;无需保存到不同的文件名)?
  2. 通常以“.GPS”结尾的文件名有时以“.gps”结尾(唯一不同的是情况)。我上面的代码只适用于大写文件。除了完全复制代码和更改 endswith 参数之外,我如何使其适用于这两种情况?

最后,我的文件需要看起来像这样:

Trace #1 at position 0.004610 
$GNGGA,233701.00,3731.1972590,S,14544.3073733,E,4,09,1.0,514.675,M,,,0.49,3023*27 
Trace #6 at position 0.249839 
$GNGGA,233706.00,3731.1971997,S,14544.3075178,E,4,09,1.0,514.689,M,,,0.71,3023*2F 

有什么建议吗?提前致谢。 :)

请您参考如下方法:

你快到了。

import os 
 
indir = '/Users/dhunter/GRID01/'  # input directory 
for i in os.listdir(indir):  # for each "i" (iteration) within the indir variable directory... 
    if i.endswith('.GPS'):  # if the filename of an iteration ends with .GPS, then... 
        print(i + ' loaded')  # print the filename to CLI, simply for debugging purposes. 
        with open(indir + i, 'r') as my_file:  # open the iteration file 
            for line in my_file: 
                if not line.startswith('$GNGSA') and not line.startswith('$GNVTG'): 
 
                    print(line)