如何在python中删除一行?

时间:2014-04-08 08:29:31

标签: string python-2.7

2331,0,13:30:08,25.35,22.05,23.8,23.9,23.5,23.7,5455,350,23.65,132,23.6,268,23.55,235,23.5,625,23.45,459,23.7,83,23.75,360,23.8,291,23.85,186,23.9,331,0,1,25,1000,733580089,name,,,

我有一条这样的线,怎么可以剪掉它?我只需要像这样的第一个9变量:

2331,0,13:30:08,25.35,22.05,23.8,23.9,23.5,23.7,5455

原始数据我保存为txt.file,我可以重写原始数据并保存吗?

3 个答案:

答案 0 :(得分:2)

使用csv或仅使用字符串split函数直接归档io

例如:

import csv
with open('some.txt', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row[:9]

或者如果一切都在一行而您不想使用csv界面

with open('some.txt', 'r') as f:
    line = f.read()
    print line.split(str=",")[:9]

答案 1 :(得分:0)

如果您的所有值都存储在数组中,则可以像这样切片:

arrayB = arrayA[:9]

要将值放入数组,可以在每个“,”

处拆分String
arrayA = inputString.split(str=",")

答案 2 :(得分:0)

如果您有一个名为" content.txt"。

的文件
f = open("content.txt","r")
contentFile = f.read();
output = contentFile.split(",")[:9] 
output = ",".join(output)
f.close()

f = open("content.txt","wb")
f.write(output)