1,105,546 Community Members

Split String Problem

Member Avatar
mr_noname
Newbie Poster
1 post since Feb 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hey. I'm pretty new in Python. I'm trying to read from my file all the content and put it in a string. My file looks:

1 string1
2 string2
10 string 3

and I want to obtain: ["1", "string1", "2", "string 2", "10", "string3"] using this:

def read(self):
        file = open("Repository/file.txt", 'r')
        f = file.readlines()
        f = f.split(" ")
        print f

but I get this: AttributeError: 'list' object has no attribute 'split'

Thanks!

Member Avatar
Gribouillis
Posting Maven
3,456 posts since Jul 2008
Reputation Points: 1,140 [?]
Q&As Helped to Solve: 884 [?]
Skill Endorsements: 18 [?]
Moderator
 
1
 

Use f = file.read() and f = f.split() .

Question Answered as of 2 Years Ago by Gribouillis
Member Avatar
snippsat
Veteran Poster
1,041 posts since Aug 2008
Reputation Points: 483 [?]
Q&As Helped to Solve: 382 [?]
Skill Endorsements: 10 [?]
 
1
 
with open('numb.txt') as f:
    print [i.split() for i in f]
    #[['1', 'string1'], ['2', 'string2'], ['10', 'string3']]

A little mistake like this for 1 list.

with open('numb.txt') as f:
    print f.read().split()
    #['1', 'string1', '2', 'string2', '10', 'string3']
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: