简体   繁体   English

以特定格式从文本文件导入Python

[英]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 "," 我的问题是,当我尝试执行以下代码时,它将所有内容输出为包含列表的字符串,我的目标是让3个字符串和一个列表传递给另一个函数,我想用“,”分隔它们

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() 添加一个','split()infile = open('todo.txt')。read()。splitlines()

for line in infile: print(line.split(',')) 对于infile中的行:print(line.split(','))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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