简体   繁体   中英

Import from a text file in a specific format Python

I am currently trying to read in from a text file that looks like so:

10/11/17, 10:00, 02:00, [mary, john, scott]

11/11/17, 12:00, 01:30, [ashley, john, sarah]

12/11/17, 12:00, 03:00, [steve, mick]

and I want the program to read in the files as individual elements:

"10/11/17", "10:00", "02:00", [mary, john, scott]

"11/11/17", "12:00", "01:30", [ashley, john, sarah]

"12/11/17", "12:00", "03:00", [steve, mick]

My problem is that when i try do the following code it outputs everything as a string including the list, I'm aiming to have 3 strings and a list to pass through to another function, I would like to separate them by ","

infile = open('todo.txt').read().splitlines()

for line in infile:
    print(line.split())

First, split the lines into their four parts, and then do some fancy magic with the last element in the list:

for line in infile:
    line_list = line.split(', ', maxsplit=3)
    line_list[3] = line_list[3].strip("[]").split(', ')

Add a ',' is split() infile = open('todo.txt').read().splitlines()

for line in infile: print(line.split(','))

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