![](/img/trans.png)
[英]How to convert a string to list in python, the string is read from a text file
[英]Read and convert row in text file into list of string
我有一個包含2行文本的文本文件data.txt
。
first_row_1 first_row_2 first_row_3
second_row_1 second_row_2 second_row_3
我想讀取文本文件的第二行,並將內容轉換為python中的字符串列表。 列表應該如下所示;
txt_list_str=['second_row_1','second_row_2','second_row_3']
這是我嘗試過的代碼;
import csv
with open('data.txt', newline='') as f:
reader = csv.reader(f)
row1 = next(reader)
row2 = next(reader)
my_list = row2.split(" ")
我得到了錯誤AttributeError: 'list' object has no attribute 'split'
我正在使用python v3。
編輯:謝謝你的所有答案。 我相信所有這些都有效。 但有人可以告訴我自己嘗試的代碼有什么問題嗎? 謝謝。
你的代碼不起作用的原因是你試圖在列表上使用split
,但它意味着在字符串上使用。 因此,在您的示例中,您將使用row2[0]
來訪問列表的第一個元素。
my_list = row2[0].split(" ")
或者,如果您可以訪問numpy
庫,則可以使用loadtxt 。
import numpy as np
f = np.loadtxt("data.txt", dtype=str, skiprows=1)
print (f)
# ['second_row_1' 'second_row_2' 'second_row_3']
結果是數組而不是列表。 如果需要列表,可以簡單地將數組轉換為列表
print (list(f))
#['second_row_1', 'second_row_2', 'second_row_3']
使用read file方法打開文件。
例如
>>> fp = open('temp.txt')
使用文件內置生成器通過下一個方法迭代行,並忽略第一行。
>>> next(fp)
'first_row_1 first_row_2 first_row_3)\n'
在任何變量中獲取第二行。
>>> second_line = next(fp)
>>> second_line
'second_row_1 second_row_2 second_row_3'
使用拆分字符串方法獲取列表中的項目。 split方法取一個或零參數。 如果沒有給他們分開使用白色空間進行拆分。
>>> second_line.split()
['second_row_1', 'second_row_2', 'second_row_3']
最后關閉文件。
fp.close()
注意:有多種方法可以獲得相應的輸出。 但是你應該首先嘗試DavidG在評論中說。
with open("file.txt", "r") as f:
next(f) # skipping first line; will work without this too
for line in f:
txt_list_str = line.split()
print(txt_list_str)
產量
['second_row_1', 'second_row_2', 'second_row_3']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.