如何使txt文件中的每一行成为列表?

时间:2019-03-20 10:52:28

标签: python list

我有按字母顺序排列的文本文件,在Python中看起来像这样:

At 210.001 \n Au 196.9665 \n B 10.81 \n Ba 137.34 \n

我如何使每一行成为列表?要使其成为列表,字母和数字之间的空格必须为“,”,我该怎么做?

2 个答案:

答案 0 :(得分:0)

使用replace(),替换空格:

list.txt:

At 210.001
Au 196.9665
B 10.81
Ba 137.34

因此

logFile = "list.txt"

with open(logFile) as f:
    content = f.readlines()      
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]        
for line in content:     
    print([line.replace(" ", ",")])  # for each line, replace the space with ,

输出

['At,210.001']
['Au,196.9665']
['B,10.81']
['Ba,137.34']

答案 1 :(得分:0)

您可以使用以下代码:

with open('list.txt', 'r') as myfile:
    data=myfile.read()
    print([i.strip().split() for i in data.split(' \\n') if len(i.strip())>0])

输出:

[['At', '210.001'], ['Au', '196.9665'], ['B', '10.81'], ['Ba', '137.34']] 

如果要将第二个元素转换为float,则将代码更改为:

def floatify_list_of_lists(nested_list):
    def floatify(s):
      try:
        return float(s)
      except ValueError:
        return s
    def floatify_list(lst):
        return [floatify(s) for s in lst]
    return [floatify_list(lst) for lst in nested_list]

with open('list.txt', 'r') as myfile:
    data = myfile.read()
    print(floatify_list_of_lists([i.strip().split() for i in data.split(' \\n') if len(i.strip())>0]))

输出:

[['At', 210.001], ['Au', 196.9665], ['B', 10.81], ['Ba', 137.34]] 

如果确实需要在所有嵌套行中使用一个字符串,请使用:

with open('list.txt', 'r') as myfile:
    data=myfile.read()
    print([[i.strip().replace(' ',',')] for i in data.split(' \\n') if len(i.strip())>0])

输出:

[['At,210.001'], ['Au,196.9665'], ['B,10.81'], ['Ba,137.34']]