如何在python中删除文件某些行中的额外字符

如何在python中删除文件某些行中的额外字符,python,Python,如果这个描述还不够,我可以包含一个代码示例,以进一步了解错误的来源。目前,我有一个文件,我正在导入,看起来像以下 0.9,0.9,0.12 0.,0.75,0.16 0.7,0.75,0.24 0.7,0.75,0.32 0.5,0.,0.1 0.6,0.65,0.38 0.6,0.8,0., 0.9,0.95,0.04 0.5,0.65,0.28 在倒数第三行,0后面有一个逗号。最后一列的,看起来像0。,。因此,我得到了错误 Some errors were detected ! Line

如果这个描述还不够,我可以包含一个代码示例,以进一步了解错误的来源。目前,我有一个文件,我正在导入,看起来像以下

0.9,0.9,0.12
0.,0.75,0.16
0.7,0.75,0.24
0.7,0.75,0.32
0.5,0.,0.1
0.6,0.65,0.38
0.6,0.8,0.,
0.9,0.95,0.04
0.5,0.65,0.28
在倒数第三行,0后面有一个逗号。最后一列的,看起来像0。,。因此,我得到了错误

Some errors were detected !
Line #7 (got 4 columns instead of 3)
对于我的代码,我使用

%matplotlib notebook
import numpy as np                           #import python tools
import matplotlib.pyplot as plt
from numpy import genfromtxt
from mpl_toolkits.mplot3d import Axes3D

file = 'graph'    
info = genfromtxt(file, delimiter=',') 

beaming = info[:,0]
albedo = info[:,2]
diameter = info[:,1]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(diameter, albedo, beaming, c='r', marker='o')

ax.set_xlabel('diameter (km)')
ax.set_ylabel('albedo')
ax.set_zlabel('beaming parameter')

plt.show()

也许有一种方法可以忽略逗号并在前3列中显式读取,或者有一种方法可以去掉逗号,但我不确定。任何建议都有帮助

您可以通过以下方式删除所有逗号并将其重新保存为新文件:

with open("file.txt") as fi, open("out.txt", "w") as fo:
    for line in fi:
        line = line.strip()
        if line[-1] == ",":
            line = line[:-1]
        fo.write(line + "\n")

为什么不先自己编辑这个文件呢?我这么做了,效果很好。我唯一的问题是有很多这些文件都有相同的问题威尔,这些文件是从哪里来的?也许您可以在源代码处修复它?您还可以指定您感兴趣的列,即info=genfromtfile,delimiter=',',usecols=0,1,2