user3425118
user3425118

Reputation: 23

How to cut a line in python?

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,,,

I got a line like this and how could I cut it? I only need the first 9 variable like this:

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

the original data i save as txt.file, and could I rewrite the original one and save?

Upvotes: 0

Views: 4195

Answers (3)

Mailerdaimon
Mailerdaimon

Reputation: 6080

If all your values are stored in an Array, you can slice like this:

arrayB = arrayA[:9]

To get your values into an array you could split your String at every ","

arrayA = inputString.split(str=",")

Upvotes: 0

Fmrubio
Fmrubio

Reputation: 365

If you have a file called "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)

Upvotes: 0

photoionized
photoionized

Reputation: 5232

Use either csv or just to straight file io with string split function

For example:

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

or if everything is on a single line and you don't want to use a csv interface

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

Upvotes: 2

Related Questions