[英]Read and convert row in text file into list of string
I have a text file data.txt
that contains 2 rows of text. 我有一个包含2行文本的文本文件
data.txt
。
first_row_1 first_row_2 first_row_3
second_row_1 second_row_2 second_row_3
I would like to read the second row of the text file and convert the contents into a list of string in python. 我想读取文本文件的第二行,并将内容转换为python中的字符串列表。 The list should look like this;
列表应该如下所示;
txt_list_str=['second_row_1','second_row_2','second_row_3']
Here is my attempted code; 这是我尝试过的代码;
import csv
with open('data.txt', newline='') as f:
reader = csv.reader(f)
row1 = next(reader)
row2 = next(reader)
my_list = row2.split(" ")
I got the error AttributeError: 'list' object has no attribute 'split'
我得到了错误
AttributeError: 'list' object has no attribute 'split'
I am using python v3. 我正在使用python v3。
EDIT: Thanks for all the answers. 编辑:谢谢你的所有答案。 I am sure all of them works.
我相信所有这些都有效。 But can someone tell me what is wrong with my own attempted code?
但有人可以告诉我自己尝试的代码有什么问题吗? Thanks.
谢谢。
The reason your code doesn't work is you are trying to use split
on a list, but it is meant to be used on a string. 你的代码不起作用的原因是你试图在列表上使用
split
,但它意味着在字符串上使用。 Therefore in your example you would use row2[0]
to access the first element of the list. 因此,在您的示例中,您将使用
row2[0]
来访问列表的第一个元素。
my_list = row2[0].split(" ")
Alternatively, if you have access to the numpy
library you can use loadtxt . 或者,如果您可以访问
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']
The result of this is an array as opposed to a list. 结果是数组而不是列表。 You could simply cast the array to a list if you require a list
如果需要列表,可以简单地将数组转换为列表
print (list(f))
#['second_row_1', 'second_row_2', 'second_row_3']
Use read file method to open file. 使用read file方法打开文件。
Eg 例如
>>> fp = open('temp.txt')
Use file inbuilt generator to iterate lines by next method, and ignore first line. 使用文件内置生成器通过下一个方法迭代行,并忽略第一行。
>>> next(fp)
'first_row_1 first_row_2 first_row_3)\n'
Get second line in any variable. 在任何变量中获取第二行。
>>> second_line = next(fp)
>>> second_line
'second_row_1 second_row_2 second_row_3'
Use Split string method to get items in list. 使用拆分字符串方法获取列表中的项目。 split method take one or zero argument.
split方法取一个或零参数。 if not given they split use white space for split.
如果没有给他们分开使用白色空间进行拆分。
>>> second_line.split()
['second_row_1', 'second_row_2', 'second_row_3']
And finally close the file. 最后关闭文件。
fp.close()
Note: There are number of way to get respective output. 注意:有多种方法可以获得相应的输出。 But you should attempt first as DavidG said in comment.
但是你应该首先尝试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)
Output 产量
['second_row_1', 'second_row_2', 'second_row_3']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.