简体   繁体   中英

How can I use split() function with file?

I have a txt file contain a list of phone numbers and the duration between two number have contacted with each other like this:

3058 1234 2:28
1650 00777666555 2:03
3928 00423775651 4:54
2222 3333 5:20
3058 00876543210 1:49
3058 1234 1:15
1650 00876543210 2:10
2222 1234 2:32
3928 00172839456 1:38
1111 00969633330 3:01 

Let call this txt file is calls.txt. So i try to make a function which can separate the number of each line into 3 variable is firstNumber , secondNumber and duration . This is my code:

def splitLine():
    with open('calls.txt') as file:
       lines = file.readlines()
       lines.split(" ")
splitLine()

I know it won't give me any result but i still run it just to see if there is any bug come up. And of course the bug i received is:

'list' object has no attribute 'split'

So i did try a lot of times with that split() function but still got the same bug. Could anyone let me know what is this bug and how I can use the split() function in right way ?

You are reading the all the lines here:

       lines = file.readlines()

and trying to split the list created.

Instead, you should loop the lines into single individual lines such as :

for line in lines: 
    line.split()

then split it as above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM