热跳过txt文件python中的特殊字符

时间:2017-03-17 08:05:38

标签: python character skip

我在阅读txt文件时遇到了一些问题。我要做的是读取文件(约360)并制作情节。一切都有效,除非我的文件中有一个特殊的字符,比如我们:“”。当我的阅读功能发现该角色崩溃时。有没有办法跳过它?我的代码:

import os
import matplotlib.pyplot as plt
import numpy as np

i = 10
j = 0
X = []
Y = []
Z = []
k = 0
A = np.zeros([360,719])

for i in range(10,360,10):
        X = []
        Y = []
        if len(str(i)) == 2:
            data = open(dir + '\\150317_ScPONd_0%s_radio.txt'%i, 'r')
        else:
            data = open(dir + '\\150317_ScPONd_%s_radio.txt'%i, 'r')
        z = data.readlines()
        data.close()
        for line in z:
            if not line.startswith('$'):
                data_2 = line.split('\t')
                X.append(data_2[0])
                Y.append(data_2[1])
        A[j,:] = X
        A[(j+1),:] = Y

以下是我的文件的样子: enter image description here 有没有办法跳过那些“$”行?对不起那张照片,我不知道如何更好地附上它。

2 个答案:

答案 0 :(得分:0)

向@ user1753919致谢我找到了答案。如果有人仍然对此感兴趣,这里有代码:

for i in range(10,360,10):
        X = []
        Y = []
        if len(str(i)) == 2:
            data = np.genfromtxt(dir + '\\150317_ScPONd_0%s_radio.txt'%i,skip_header = 12)
        else:
            data = np.genfromtxt(dir + '\\150317_ScPONd_%s_radio.txt'%i,skip_header = 12)
        for line in data:
            X.append(line[0])
            Y.append(line[1])
        A[j,:] = X
        A[(j+1),:] = Y
        plt.plot(A[j,:],A[(j+1),:],label = '{} K'.format(i))
        plt.hold
        j = j+2

答案 1 :(得分:0)

genfromtxt有点矫枉过正。

np.loadtxt(file, comments='$')
相关问题