您可以定义自己的分隔符的分裂你的字符串(或文件行)与模块re
https://docs.python.org/3/library/re.html。使用with open()
表示在代码中的with open()
缩进结束后文件链接关闭。
我用list comprehension
这里,因为它比一个for循环略快于构造列表
import re
def return_lines_split_by_choice(delimiters,path):
re_pattern = '|'.join(map(re.escape,delimiters))
with open(path) as file_handle:
return [re.split(re_pattern,line.rstrip()) for line in file_handle]
my_list_of_lists = return_lines_split_by_choice((" ",","),my_filepath)
只要把你的分隔符,或事物的选择,在这里(" ",",")
结果是将行拆分:
for sublist in my_list_of_lists:
print (sublist)
['1.', '27.01.1957', '8', '12', '31', '39', '43', '45']
['2.', '03.02.1957', '5', '10', '11', '22', '25', '27']
['3.', '10.02.1957', '18', '19', '20', '26', '45', '49']
['4.', '17.02.1957', '2', '11', '14', '37', '40', '45']
['5.', '24.02.1957', '8', '10', '15', '35', '39', '49']
['6.', '03.03.1957', '24', '26', '31', '35', '43', '47']
['7.', '10.03.1957', '13', '20', '23', '29', '38', '44']
如果你只是想行的列表使用这个功能来代替:
def list_of_lines(path):
with open(path) as file_handle:
return [line.rstrip() for line in file_handle]
这样,只要运行它:
my_list_of_lists = list_of_lines(my_filepath)
如果你的Python程序在同一文件夹中的TXT文件,然后你的文件路径可以只是像这样"mytxt.txt"
否则你可以使用的文件名os
模块为您的操作系统规范化一个文件路径
list的列表需要什么形式?每行三个元素?更多?减?您提供的输入可以有效地产生许多不同的输出。 – ShadowRanger