在 python 中读取没有评论的文件

Reading a file with without comments in python

我需要读取 python 中的文件。我的问题是,该文件有交替数量的列,并且每行末尾都有注释。我想在读取文件时删除注释并将数据保存在数组或类似的东西中。我完全不知道该怎么做。你们中的任何人都可以帮助我吗? 这是文件的样子:

2.0#质量

-2.0 2.0 1999 # xMin xMax nPoint

1 5 # 要打印的第一个和最后一个特征值

linear #插值类型

2#编号。插值点和 xy 声明

-2.0 0.0

2.0 0.0

您的数据存储在 csv 中吗?如果是,那么这个解决方案应该有效(不过我还没有测试过)。如果它不是 csv,那么您可以调整它以匹配您的来源:

import csv
data=[]
with open('C:\data.csv', 'r') as csvfile:
    csvreader = csv.reader(csvfile, delimiter = ',')
    for row in csvreader:
        datarow=[]
        for col in row:
            if not col.startswith('#'):
                datarow.append(col)
        data.append(datarow)

您的数据行(数组)将包含最终数据,减去注释。让我知道它是否有效!

data.txt:

2.0 # mass

-2.0 2.0 1999 # xMin xMax nPoint

1 5 # first and last eigenvalue to print

linear # interpolation type

2 # nr. of interpolation points and xy declarations

-2.0 0.0

2.0 0.0

main.py:

#open file and write into "content"
with open('data.txt', 'r') as f:
    content = f.readlines()

datalines=[]

for line in content:

    # remove linebreaks
    newline = line.replace('\n','')

    # find start of comments
    location = newline.find('#')
    # if line has no comment location = -1
    if location >= 0:
        # write into "newline" without comment, remove whitespaces at start and end with strip
        newline = newline[0:location].strip()

    # only append if line is not empty
    if newline is not '':
        datalines.append(newline)

# print
print(datalines)

打印:

['2.0', '-2.0 2.0 1999', '1 5', 'linear', '2', '-2.0 0.0', '2.0 0.0']

如果你愿意,我写了一个 python 模块 IO 使文件读取变得容易,允许你忽略注释,即使在行的中间。我正在 GitHub

上开发它

data.txt

2.0 # mass

-2.0 2.0 1999 # xMin xMax nPoint

1 5 # first and last eigenvalue to print

linear # interpolation type

2 # nr. of interpolation points and xy declarations

-2.0 0.0

2.0 0.0

python代码只有两行

In [1]: import IO
In [2]: data = IO.readfile("data.txt").tolist()   # Returns a numpy object instead

Warning: not all lines have the same shape
Most frequent lenght : 2 (4 counts) 
Check rows :  0  1  

如您所见,如果行中的元素数量不同(因为我写这个是为了读取表格数据),模块甚至会向您发出警告

输出为

In [3]: data
Out[3]: 
[[2.0],
 [-2.0, 2.0, 1999.0],
 [1.0, 5.0],
 [2.0, 0.0],
 [-2.0, 0.0],
 [2.0, 0.0]]

不幸的是,这不适用于字符串,因此您可能希望 select 带有数字的插值类型(即线性 = 1、二次 = 2、立方 = 3 等)

l = []
with open('data.txt', 'r') as f:
    for line in f:
        l.append(line.split('#')[0].split())
print(l)

# Output:
# [[2.0], [-2.0, 2.0, 1999], [1, 5], [linear], [2], [-2.0, 0.0], [2.0, 0.0]]